抽象类
什么是抽象类
观察下面这个例子
class Shape {
public void draw() {
System.out.println("画图形");
}
}
class Circle extends Shape {
public void draw() {
System.out.println("圆型");
}
}
public class TestDemo {
public static void main(String[] args) {
Shape shape = new Circle();
shape.draw();
}
}
从图中得知 由于动态绑定 父类引用调用方法 只会去执行子类的方法 不会去调用父类
也就是说 父类方法的存在只是为了让子类去重写 发生动态绑定
此时,我们就可以在这个父类方法前面加 abstract关键字修饰 表示抽象方法
由于抽象方法的存在 包含抽象方法的类也必须加上abstract修饰 此时这个类叫做抽象类
抽象类中的重点总结
1. 抽象方法不能有主体 所以没有具体实现
2. 如果一个类中有抽象方法 那么这个类必须用abstract修饰 此时这个类叫做抽象类
3. 抽象类中可以有与普通类一样的成员变量和方法
4. 与普通类不同的是 不能使用抽象类实例化对象
abstract class Shape {
public int a;
public abstract void draw();
}
class Circle extends Shape {
public void draw() {
System.out.println("圆型");
}
}
public class TestDemo {
public static void main(String[] args) {
Shape shape = new Shape();
}
}
5. 当一个普通类继承这个抽象类 普通类必须重写父类中的抽象方法
6. 抽象类就是为了让子类继承 重写 发生动态绑定 发生多态
只是 子类继承抽象类后 编译器会检验 子类是否重写了抽象类中的抽象方法 加了一层重写检验
abstract class Shape {
public abstract void draw();
}
class Circle extends Shape {
public void draw() {
System.out.println("圆型");
}
}
class Triangle extends Shape {
public void draw() {
System.out.println("画三角");
}
}
class Square extends Shape {
@Override
public void draw() {
System.out.println("画方形");
}
}
public class TestDemo {
public static void func(Shape shape) {
shape.draw();
}
public static void main(String[] args) {
//Shape shape = new Shape();
Shape shape = new Circle();
func(shape);
shape = new Triangle();
func(shape);
shape = new Square();
func(shape);
}
}
7. 抽象方法不能被 private final static修饰 因为抽象方法就是为了被重写的,而private final static修饰后方法不能重写
8. 如果普通类继承抽象类后 普通类不重写抽象类中抽象方法 那么这个普通类必须也用abstract进行修饰 如果有类继承这个普通类 那么这个类必须重写普通类和抽象类的抽象方法
如下例:
9. 抽象类中可以没有抽象方法 但是有抽象方法的类一定是抽象类
10. 抽象类中可以有构造方法
为什么抽象类不能实例化对象 但是抽象类有构造方法 ?
抽象类中的构造方法 不是用来实例化抽象类的对象 而是在子类中调用 帮助父类初始化 从而给子类初始化
abstract class Person {
String name;
int age;
public Person(String name,int age) {
this.name = name;
this.age = age;
}
}
class Student extends Person {
public Student(String name,int age) {
super(name,age);
}
public void print() {
System.out.println(this.name + " " + this.age);
}
}
public class TestDemo {
public static void main(String[] args) {
Student stu = new Student("小白",18);
stu.print();
}
}