在Java中覆盖成员变量 [英] Overriding member variables in Java

查看:80
本文介绍了在Java中覆盖成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究在JAVA中覆盖成员函数,并考虑尝试重写成员变量。

I am studying overriding member functions in JAVA and thought about experimenting with overriding member variables.

所以,我定义了类

public class A{
    public int intVal = 1;
    public void identifyClass()
    {
        System.out.println("I am class A");
    }
}

public class B extends A
{
    public int intVal = 2;
    public void identifyClass()
    {
        System.out.println("I am class B");
    }
}

public class mainClass
{
    public static void main(String [] args)
    {
        A a = new A();
        B b = new B();
        A aRef;
        aRef = a;
        System.out.println(aRef.intVal);
        aRef.identifyClass();
        aRef = b;
        System.out.println(aRef.intVal);
        aRef.identifyClass();
    }
}

输出为:

1
I am class A
1
I am class B

我无法理解为什么当aRef设置为b时,intVal仍属于A类?

I am not able to understand why when aRef is set to b intVal is still of class A?

推荐答案

当您在子类中创建同名变量时,称为隐藏。生成的子类现在实际上具有两个属性。您可以使用 super.var ((SuperClass))来访问超类中的那个.var 。变量甚至不必是同一类型;它们只是两个共享名称的变量,就像两个重载方法一样。

When you make a variable of the same name in a subclass, that's called hiding. The resulting subclass will now actually have both properties. You can access the one from the superclass with super.var or ((SuperClass)this).var. The variables don't even have to be of the same type; they are just two variables sharing a name, much like two overloaded methods.

这篇关于在Java中覆盖成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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