我有这个例子:
class One
{
public void testOne(){System.out.println("One!!!");}
public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
static void test(One o) {o.testOne(); o.testTwo();}
public static void main(String args[])
{
test(new One());
}
}结果:
One!!!
One!!!好了,没有问题了。
然后,我试着修改我的代码:
仅此方法:
public static void main(String args[])
{
test(new Jenia());
}结果:
One!!!
One!!!好的,我们有这样的结果是因为-这里向上转换(Jenia-One)。
也可以,但是,再次修改:在class Jenia override methodtestOne`中:
public void testOne(){System.out.println("Two!!!");}所以我有这样的代码:
class One
{
public void testOne(){System.out.println("One!!!");}
public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
public void testOne(){System.out.println("Two!!!");}
static void test(One o){o.testOne(); o.testTwo();}
public static void main(String args[])
{
test(new Jenia());
}
}和结果:
Two!!!
One!!!我的问题:为什么是两个!??为什么我们没有丢失覆盖方法?
发布于 2010-12-14 16:12:10
因为Java中的所有方法在C++/C#和所有通过引用传递的值方面都是虚拟的。所以当你调用一些方法时,引用的类型是不相关的,重要的是它所指向的对象的类型。在本例中,对象是Jenia类型,因此调用Jenia方法。
发布于 2010-12-14 16:11:20
这就是我们想要的行为。调用哪个方法取决于运行时类型,而不是引用类型。由于obect的类型为Jenia,因此即使引用的类型为One,也会调用testOne的Jenia版本。这就是普通的老多态。
发布于 2010-12-14 16:10:01
请参阅评论中的说明
class One
{
public void testOne(){System.out.println("One!!!");}//method one
public void testTwo(){System.out.println("One!!!");}//method two
}
public class Jenia extends One
{
public void testOne(){System.out.println("Two!!!");}//method 3
static void test(One o){o.testOne(); o.testTwo();}//method 4
public static void main(String args[])
{
test(new Jenia());//calls method 4 which in turns calls 3 and 2.
}
}
}https://stackoverflow.com/questions/4437066
复制相似问题