抽象
概述
抽象类中不一定有抽象方法,有抽象方法的一定是抽象类。
在面向对象的概念中,所有的对象都是通过类来描绘的,但是反过来,并不是所有的类都是用来描绘对象的,如果一个类中没有包含足够的信息来描绘一个具体的对象,这样的类就是抽象类。
特点:
1、 抽象类不能实例化(可通过多态实现)
2、有构造方法
子类特点
A:子类是抽象的
B:子类不抽象(必须重写所有抽象方法)
成员特点
成员变量
变量、常量均可以。
构造方法
有。
成员方法
A:抽象:强制要求子类做的事
B:非抽象:子类继承的是
分析--------具体------->抽象
实现--------抽象-------->具体
注意
1、 一个抽象类可以没有抽象方法。意义:不让外界创建对象
2、abstract与关键字组合
private:冲突(父类私有成员不能被继承,方法不能被重写)
final:冲突
static:无意义。
代码案例:
public class AbstractTest {
public static void main(String[] args) {
//方式一
Dog d = new Dog();
d.setName("旺财");
d.setAge(3);
System.out.println(d.getAge()+"......"+d.getName());
d.eat();
//方式二
Dog d1 = new Dog("小花",3);
System.out.println(d1.getAge()+"......"+d.getName());
d1.eat();
//方式三
Animal a = new Dog();
a.setName("旺财");
a.setAge(3);
System.out.println(a.getAge()+"......."+a.getName());
a.eat();
}
}
abstract class Animal {
// 姓名
private String name;
// 年龄
private int age;
public Animal() {
}
public Animal(String name, int age) {
this.age = age;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// 抽象方法
public abstract void eat();
}
// 定义具体类
class Dog extends Animal {
public Dog() {
}
public Dog(String name, int age) {
super(name, age);
}
public void eat() {
System.out.println("狗吃肉");
}
}
class Cat extends Animal {
public Cat() {
}
public Cat(String name, int age) {
super(name, age);
}
public void eat() {
System.out.println("猫吃鱼");
}
}