是由引用变量定义的成员类的类型还是它指向的内容? [英] Is the type of member class defined by the reference variable or what it points to ?

查看:121
本文介绍了是由引用变量定义的成员类的类型还是它指向的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,当我用p调用foo方法时,它获取子类中的一个,但是当我访问num变量时,它获取父类中的一个,因此基于引用变量类型的成员类型或者是什么它指向的对象?



in the example below when i call the foo method with p it gets the one in child class but when i access the num variable it gets the one in parent class, so is the member type based on the reference variable type or what object it points to ?

public class Main {

    public static void main(String[] args) {
    Parent p=new Child();
        System.out.println(p.num);
        p.foo();

    }

}


class Parent {
    public int num = 10;

    void foo() {
        System.out.println("Foo in parent");
    }
}


class Child extends Parent {
    public int num = 100;
    @Override
    void foo() {
        System.out.println("Foo in Child");
    }
}





我的尝试:



i不要在这里填写什么,所以这只是随机的,对不起!



What I have tried:

i don't what to fill in here so this is just random, sorry !

推荐答案

你有一个覆盖为了foo;但不是数字;和孩子被视为父母;所以它适用于parent.num。



这些是差异。
You got an "override" for foo; but not num; and child is cast as a "parent"; so it goes for parent.num.

Those are the differences.


这篇关于是由引用变量定义的成员类的类型还是它指向的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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