Home > Back-end >  In 16 years soft -- not see a problem, the method of super is how to invoke printInvoice (), don
In 16 years soft -- not see a problem, the method of super is how to invoke printInvoice (), don

Time:10-30

Code:
Public class Invoice {
Public void printInvoice () {
System. Out.println (" This is the content of the invoice!" );
}
}
The class Decorator extends Invoice {
Protected Invoice ticket;
Public Decorator (Invoice t) {
Ticket=t;
}
Public void printInvoice () {
If (ticket!=null) {
Ticket. PrintInvoice ();
}
}
}
The class HeadDecorator extends the Decorator {
Public HeadDecorator (Invoice t) {
Super (t);
}
Public void printInvoice () {
System. Out.println (" This is the header of an invoice!" );
Super. PrintInvoice ();
}
}
The class FootDecorator extends the Decorator {
Public FootDecorator (Invoice t) {
Super (t);
}
Public void printInvoice () {
Super. PrintInvoice ();
System. Out.println (" This is the footnote of the invoice!" );
}
}
The class test {
Public static void main (String [] args) {
Invoice t=new Invoice ();
Invoice ticket;
Ticket=new HeadDecorator (new FootDecorator (t));
Ticket. PrintInvoice ();
System. The out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- ");
Ticket=new HeadDecorator (new FootDecorator (null));
Ticket. PrintInvoice ();
}
}
Output:
This is the header of the invoice!
This is the content of the invoice!
This is the footnote of the invoice!
-- -- -- -- -- -- -- -- -- -- -- -- --
This is the header of the invoice!
This is the footnote of the invoice!

Want to ask next super call methods is how to call, just call it again?

CodePudding user response:

Look pretty disgusting, and understood the debug walk again, and the output for the first time, the actual type is the header, ticket attribute type is a foot, the second is the actual type foot, ticket attribute type is an Invoice,,
So the order is the header - & gt; The content - & gt; Invoice
"-- -- -- -- -- -- -- -- -- -- -- -- --" don't look back, thinking is the same,

CodePudding user response:

Two ways, 1. Super
2. The parent class defines an abstract method, subclass to be realized
  • Related