-
abstract:抽象的。可以用来修饰类、方法
-
abstract 修饰类:抽象类
-
此类不能实例化(就是不能被main函数实例化,但是能被其子类对象实例化)
-
仍然提供构造器,便于子类是实例化的时候调用
-
开发中,都会提供抽象类的子类,让子类对象实例化完成相关操作
public class test { public static void main(String[] args) { Student s1 = new Student(18, "a"); s1.eat(); /* eat */ s1.walk(); /* walk */ } } abstract class Person { int age; String name; Person() { } public Person(int age, String name) { this.age = age; this.name = name; } public void eat() { System.out.println("eat"); } public void walk() { System.out.println("walk"); } } class Student extends Person { public Student(int age, String name) { super(age, name); // 调用父类的构造器 } }
-
-
abstract 修饰方法:抽象方法
-
抽象方法只有方法的声明没有方法体。
-
抽象方法只存在抽象类中,抽象类不一定有抽象方法
-
子类继承了有抽象方法的抽象类,必须对继承的所有抽象方法重写方可实例化;或者子类也是抽象类,抽象方法不用全部重写
public class test { public static void main(String[] args) { heightSchoolStudent h = new heightSchoolStudent(18, "a"); h.eat();/* eat */ h.run();/* run */ h.walk();/* walk */ } } abstract class Person { int age; String name; public Person(int age, String name) { this.age = age; this.name = name; } public abstract void eat(); // 抽象方法被继承 public void walk() { System.out.println("walk"); } } abstract class Student extends Person { public Student(int age, String name) { super(age, name); // 调用父类的构造器 } public abstract void run(); // 抽象方法被继承 } class heightSchoolStudent extends Student { public heightSchoolStudent(int age, String name) { super(age, name); // 调用父类的构造器 } public void eat() { System.out.println("eat"); // 抽象类Person的抽象方法被重写 } public void run() { System.out.println("run"); // 抽象类Student的抽象方法被重写 } }
-
-
abstract 使用注意点
- 不能用来修饰属性、构造器等结构
- 不能修饰私有方法、静态方法、final 方法