实例:老师黑板上抄作业,甲同学错了题,就算再聪明也答不对啊,既然题目都是一样的,就吧题目抽出来,仅提供填写答案的地方。模板方式就产生了
abstract class Question {
void ques1() {
System.out.println("1+1 = " + answer1());
}
void ques2() {
System.out.println("1+2 = " + answer2());
}
void ques3() {
System.out.println("1+3 = " + answer3());
}
abstract int answer1();
abstract int answer2();
abstract int answer3();
}
同时抽出答案的方法,让学生实现
学生甲
public class Student extends Question {
@Override
int answer1() {
return 2;
}
@Override
int answer2() {
return 3;
}
@Override
int answer3() {
return 4;
}
}
学生乙
public class Student2 extends Question {
@Override
int answer1() {
return 2;
}
@Override
int answer2() {
return 2;
}
@Override
int answer3() {
return 4;
}
}
测试类
public class Demo { public static void main(String[] args) { System.out.println("学生甲:"); Student student = new Student(); student.ques1(); student.ques2(); student.ques3(); System.out.println("学生乙:"); Student2 student2 = new Student2(); student2.ques1(); student2.ques2(); student2.ques3(); } }
结果: