当前位置: 代码迷 >> J2SE >> java继承概念一例子打印不解解决方法
  详细解决方案

java继承概念一例子打印不解解决方法

热度:93   发布时间:2016-04-24 01:47:19.0
java继承概念一例子打印不解


 class Base {

public void foo(Base x)
{
System.out.println("Base.Base");
}
public void foo(Derived x)
{
System.out.println("Base.Derived");
}

}
class Derived extends Base
{
public void foo(Base x)
{
System.out.println("Derived.Base");
}
public void foo(Derived x)
{
System.out.println("Derived.Derived");
}

}
public class StaticParamsDemo
{
public static void whichFoo(Base arg1, Base arg2)
{
//It is guaranteed that we will call foo(Base)
//Only issue is which class's version of foo(Base)
//is called; the dynamic type of arg1 is used
//to decide
arg1.foo(arg2);
}
public static void main(String []args)
{
Base b = new Base();
Derived d = new Derived();

whichFoo(b,b);
whichFoo(b,d);
whichFoo(d,b);
whichFoo(d,d);
}
}

打印结果为:
Base.Base
Base.Base
Derived.Base
Derived.Base

想请问大虾,结果为什么不是:
Base.Base
Base.Derived
Derived.Base
Derived.Derived.

------解决方案--------------------
这个代码中继承的体现就是父类中的方法子类也有,但是会被子类Derived 覆盖
whichFoo的一个参数是什么类型,就调用对应类型的foo方法,例如,arg1是Base类型就调用Base类的foo方法,

第二个参数是什么类型,就调用该类中对应的foo方法
------解决方案--------------------
其实这段代码的突破口可以从


Java code
public class StaticParamsDemo{public static void whichFoo(Base arg1, Base arg2){arg1.foo(arg2);}public static void main(String []args){Base b = new Base();Derived d = new Derived();whichFoo(b,b); //第一个参数是[color=#FF0000]b[/color]那就是进类Base 然后调用whichFoo,那第一个参数是类Base 自然就打印出Base 类中的第一个System.out.println("Base.Base");whichFoo(b,d);//第一个参数是[color=#FF0000]b[/color]那就是进类Base 然后调用whichFoo,那第一个参数是类Base 自然就打印出Base 类中的第一个System.out.println("Base.Base");whichFoo(d,b);//第一个参数是[color=#FF0000]d[/color]那就是进类Derived然后调用whichFoo,那第一个参数是类Derived 自然就打印出Derived类中的第一个System.out.println("Derived.Base");whichFoo(d,d);//第一个参数是[color=#FF0000]d[/color]那就是进类Derived然后调用whichFoo,那第一个参数是类Derived 自然就打印出Derived类中的第一个System.out.println("Derived.Base");}}
------解决方案--------------------
Java code
public class StaticParamsDemo{public static void whichFoo(Base arg1, Base arg2){    arg1.foo(arg2);}public static void whichtwo(Base arg1,Derived arg2){    arg1.foo(arg2);}public static void main(String []args){    Base b = new Base();    Derived d = new Derived();    whichFoo(b,b);    whichtwo(b,d);    whichFoo(d,b);    whichtwo(d,d);}}
------解决方案--------------------
结果是:
Base.Base
Base.Derived
Derived.Base
Derived.Derived
------解决方案--------------------
探讨
虽然是实现了我的要求,可也违背了面向对象编程呀。

引用:

Java code

public class StaticParamsDemo
{
public static void whichFoo(Base arg1, Base arg2)
{
arg1.foo(arg2);
}
public static void whichtw……

------解决方案--------------------
摸索下创建对象的流程吧。。。
  相关解决方案