Java继承 [英] Java inheritance

查看:82
本文介绍了Java继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么打印最后我是儿童班。 ?

Why does is print last "I'm a Child Class." ?

public class Parent
{
    String parentString;
    public Parent()
    {
        System.out.println("Parent Constructor.");
    }

    public Parent(String myString)
    {
        parentString = myString;
        System.out.println(parentString);
    }

    public void print()
    {
       System.out.println("I'm a Parent Class.");
    }
} 

public class Child extends Parent
{
    public Child() {
        super("From Derived");
        System.out.println("Child Constructor.");
    }

    public void print()
    {
       super.print();
       System.out.println("I'm a Child Class.");
    }

    public static void main(String[] args)
    {
        Child child = new Child();
        child.print();
        ((Parent)child).print();
    }
}

输出:

From Derived

Child Constructor.

I'm a Parent Class.

I'm a Child Class.

I'm a Parent Class.

I'm a Child Class.


推荐答案

因为这是多态性(后期绑定)。在编译时,您指定该对象的类型为 Parent ,因此只能调用 Parent 中定义的方法。但是在运行时,当绑定发生时,在对象上调用该方法,该类型的类型为 Child ,无论它在代码中如何被引用。

Because this is an example of polymorphism (late binding). At compile time you specify that the object is of type Parent and therefore can call only methods defined in Parent. But at runtime, when the "binding" happens, the method is called on the object, which is of type Child no matter how it is referenced in the code.

令您惊讶的部分是为什么应该在运行时调用重写方法。在Java中(与C#和C ++不同),所有方法都是 virtual ,因此调用了重写方法。请参阅此示例以了解其中的差异。

The part that surprises you is why the overriding method should be called at runtime. In Java (unlike C# and C++) all methods are virtual and hence the overriding method is called. See this example to understand the difference.

这篇关于Java继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆