代碼:
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的呼叫方法是怎么呼叫的,只呼叫一次嗎?
uj5u.com熱心網友回復:
看著挺惡心的。。 debug走一遍就明白了。。第一次輸出的時候,實際型別是header,ticket屬性型別是foot,第二次實際型別是foot,ticket屬性型別是Invoice。。所以順序是 header-->content-->invoice
"-------------"后邊沒細看,思路是一樣的。
uj5u.com熱心網友回復:
兩種方式,1. super調2. 父類定義一個抽象方法,子類去實作
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/195568.html
標籤:Java EE
上一篇:如何對xml檔案中雙引號的內容進行相應的替換呀,每個要根據順序的
下一篇:Java基礎的建議
