首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

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

2012-03-09 
java继承概念一例子打印不解class Base {public void foo(Base x){System.out.println(Base.Base)}publ

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……

[解决办法]
摸索下创建对象的流程吧。。。

热点排行