java多态
Posted 千里之外kb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java多态相关的知识,希望对你有一定的参考价值。
1,父类接收子类对象不需要强转(自动转化)。子类接收父类对象需要强转
2,当子类执行super掉用父类的构造函数时,先执行完子类的方法(流程),在去调用父类的方法
class invoice{
public void printInvoice(){
System.out.println ( "This is the content of the invoice!");
}
}
class Decorator extends Invoice {
protected Invoice ticket;
public Decorator(lnvoice t){
ticket = t;
}
public void printInvoice(){
if(ticket != null)
(1) ticket.printInvoice();
}
}
class HeadDecorator extends Decorator{
public HeadDecorator(lnvoice t){
super(t);
}
public void printInvoice (){
Systent.out.println( "This is the header of the invoice! ");
(2)ticket.printInvoice() ;
}
}
class FootDecorator extends Decorator {
public FootDecorator(Invoice t){
super(t);
}
public void printlnvoice(){
( 3)ticket.printInvoice() ;
Systent.out.println( "This is the footnote of the invoice! ");
}
}
Class test {
public static void main(String[] args){
Invoice t =new Invioce();
Invoice ticket;
ticket= (4)new FootDecorator(new HeadDecorator(t)); //new HeadDecorator的时候就已经调用父类的super函数了,
ticket.printInvoice(); //再执行printInvoce函数时先由内之外执行,即先Decorator,HeadDecorator,FootDecorator
Systent.out.println(“------------------“);
ticket= new FootDecorator(new HeadDecorator(new Decorator(null)));//new Decorator的时候传null值进去,再到new HeadDecorator的时候调用父类
ticket.printInvoice(); //同上
}
}
程序的输出结果为:
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!
以上是关于java多态的主要内容,如果未能解决你的问题,请参考以下文章