Java创建了一种专门用来当做父类的类,这种类称为抽象类。目的是要求设计者依据它的格式来修改并创建新的类。 注意:由于抽象类只能作为父类,所以不能直接由抽象类创建对象,只能通过抽象类派生出新的类,再由新的类创建对象。
注意:抽象类中方法的定义有两种:一种是一般方法,另一种是抽象方法,它是以abstract关键字为开头的方法,此方法只声明了返回值的数据类型、方法名、参数,没有方法体。
eg:FirstDemo.java
abstract class Person{ //定义了一个抽象类,类名为Person String name; //声明了三个属性 name age occupation int age; String occupation; abstract String talk(); //定义了一个抽象方法 } class Student extends Person{ //定义一个类Student并继承抽象类Person public Student(String name, int age, String occupation){ //Student类的构造方法 this.name = name; this.age = age; this.occupation = occupation; } //因为这个Student类继承了抽象类Person,所以就要复写抽象类Person中所有的抽象方法 String talk() { return "学生->姓名: "+this.name+", 年龄: "+this.age+", 职业: "+this.occupation; } } class Worker extends Person{ //定义一个类Worker并继承抽象类Person public Worker(String name,int age,String occupation){ //Worker类的构造方法 this.name = name ; this.age = age ; this.occupation = occupation ; } //因为这个Student类继承了抽象类Person,所以就要复写抽象类Person中所有的抽象方法 String talk() { return "工人->姓名: "+this.name+", 年龄: "+this.age+", 职业: "+this.occupation; } } public class FirstDemo { public static void main(String[] args){ Student s = new Student("张三", 20, "学生"); Worker w = new Worker("李四", 30, "工人"); System.out.println(s.talk()); System.out.println(w.talk()); } }运行结果: 学生->姓名: 张三, 年龄: 20, 职业: 学生 工人->姓名: 李四, 年龄: 30, 职业: 工人
与一般的类一样,抽象类中也可以拥有构造方法,但是这些构造方法必须在子类中被调用 eg:SecondDemo.java
abstract class Person{ String name; int age; String occupation; public Person(String name, int age, String occupation){ this.name = name ; this.age = age ; this.occupation = occupation ; } public abstract String talk(); } class Student extends Person{ public Student(String name, int age, String occupation) { //在这里必须明确调用抽象类中的构造方法 super(name, age, occupation); } public String talk() { return "学生->姓名: "+this.name+", 年龄: "+this.age+", 职业: "+this.occupation; } } public class SecondDemo { public static void main(String[] args){ Student s = new Student("张三", 20, "学生"); System.out.println(s.talk()) ; } }运行结果: 学生->姓名: 张三, 年龄: 20, 职业: 学生