在16年软考中看到的一道题,super的方法是如何调用printInvoice(),没搞懂

仰望星空的地底人 2020-10-29 11:11:40
代码:
public class Invoice {
public void printInvoice(){
System.out.println("This is the content of the invoice!");
}
}
class Decorator extends Invoice{
protected Invoice ticket;
public Decorator(Invoice t){
ticket = t;
}
public void printInvoice() {
if (ticket!=null){
ticket.printInvoice();
}
}
}
class HeadDecorator extends Decorator {
public HeadDecorator(Invoice t){
super(t);
}
public void printInvoice(){
System.out.println("This is the header of invoice!");
super.printInvoice();
}
}
class FootDecorator extends Decorator {
public FootDecorator(Invoice t){
super(t);
}
public void printInvoice(){
super.printInvoice();
System.out.println("This is the footnote of the invoice!");
}
}
class test {
public static void main(String[] args){
Invoice t = new Invoice();
Invoice ticket;
ticket = new HeadDecorator(new FootDecorator(t));
ticket.printInvoice();
System.out.println("-------------");
ticket = new HeadDecorator(new FootDecorator(null));
ticket.printInvoice();
}
}
输出:
This is the header of invoice!
This is the content of the invoice!
This is the footnote of the invoice!
-------------
This is the header of invoice!
This is the footnote of the invoice!

想问下super的调用方法是怎么调用的,只调用一次吗?
...全文
1124 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
KeepSayingNo 2020-10-29
  • 打赏
  • 举报
回复
两种方式,1. super调 2. 父类定义一个抽象方法,子类去实现
北北啊我是 2020-10-29
  • 打赏
  • 举报
回复
看着挺恶心的。。 debug走一遍就明白了。。第一次输出的时候,实际类型是header,ticket属性类型是foot,第二次实际类型是foot,ticket属性类型是Invoice。。 所以顺序是 header-->content-->invoice "-------------"后边没细看,思路是一样的。

67,512

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧