abstract class A{ public static final String FLAG = "CHINA"; private String name = "张三"; public String getName() { return name; } public void setName(String name) { this.name = name; } public abstract void print(); //定义一个抽象方法 }
class B extends A{ //继承抽象类,覆写全部的抽象方法 public void print(){ System.out.println("FLAG="+FLAG); System.out.println("姓名="+super.getName()); } }
public class abstract_demo {
public static void main(String[] args) { // TODO 自动生成的方法存根 B b = new B(); b.print(); }
abstract class People{ private String name; private int age; 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 People(String name, int age) { //构造函数 this.name = name; this.age = age; } public void say(){ System.out.println(this.getContent()); } public abstract String getContent(); //get方法,说话的内容由子类决定 }
class Student extends People{ private float score; public Student(String name, int age,float score) { super(name, age); //调用父类的构造方法 // TODO 自动生成的构造函数存根 this.score = score; }
@Override public String getContent() { //覆写父类中的get抽象方法 // TODO 自动生成的方法存根 return "学生信息-->姓名:"+super.getName()+"年龄:"+super.getAge()+"成绩:"+this.score; } }
class Worker extends People{ private float salary; public Worker(String name, int age,float salary) { super(name, age); //调用父类的构造方法 // TODO 自动生成的构造函数存根 this.salary = salary; }
@Override public String getContent() { //覆写父类中的get抽象方法 // TODO 自动生成的方法存根 return "工人信息-->姓名:"+super.getName()+"年龄:"+super.getAge()+"薪水:"+this.salary; } }
public class abstract_demo2 {
public static void main(String[] args) { // TODO 自动生成的方法存根 Student stu = new Student("张三",18,99.0f); Worker wor = new Worker("张三",18,1000.0f); stu.say(); wor.say(); }