抽象类的定义规则:
抽象类和抽象方法都必须用abstract关键字来修饰。
抽象类不能被实例化,也就是不能用new关键字去产生对象。
抽象方法只需声明,而不需实现。
含有抽象方法的类必须被声明为抽象类,抽象类的子类必须复写所有的抽象方法后才能被实例化,否则这个子类还是个抽象类。
import java.util.SplittableRandom;
public class text {
public static void main(String[] args) {
Student P = new Student("张三", 20, "学生");
Worker S = new Worker("李四", 30, "工人");
P.talk();
S.talk();
}
}
abstract class Person { //创建一个抽象类
String name;
int age;
String occupation;
abstract void talk(); //声明一个方法
}
class Student extends Person { //继承抽象类
public Student(String name, int age, String occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
}
public void talk() { //复写抽象类的函数
System.out.println(this.occupation + "——>姓名:" +
this.name + ",年龄:" +
this.age + ",职业:" +
this.occupation + "!");
}
}
class Worker extends Person { //继承抽象类
public Worker(String name, int age, String occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
}
public void talk() { //复写抽象类的函数
System.out.println(this.occupation + "——>姓名:" +
this.name + ",年龄:" +
this.age + ",职业:" +
this.occupation + "!");
}
}