?
Animal类?
public abstract class Animal {
private String name;
public abstract void cry();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Dog类
public class Dog extends Animal{
@Override
public void cry() {
System.out.println("汪汪汪的叫");
}
}
?Cat类
public class Cat extends Animal{
@Override
public void cry() {
System.out.println("喵喵喵的叫");
}
}
?Test类
public class Test {
public static void main(String[] args) {
Animal a = new Cat();
a.cry(); //更好的支持多态
}
}
?
?
People类
public abstract class People {
/*
* 设计一个模板设计模式
* 定义一个模板方法
* */
public void write(){
System.out.println("abc");
System.out.println("张三、李四、王五");
System.out.println(writeMain());
// 模板方法并不清楚正文部分要怎么写,但它知道子类肯定要写
System.out.println("666");
}
// 设计一个抽象类方法写正文,具体实现交给子类来完成
public abstract String writeMain();
}
Teacher类
public class Teacher extends People{
@Override
public String writeMain() {
return "123456789";
}
}
Student类
public class Student extends People{
@Override
public String writeMain() {
return "987654321";
}
}
Test类
public class Test {
public static void main(String[] args) {
Teacher t = new Teacher();
t.write();
Student s = new Student();
s.write();
}
}