Java中的实例变量

发布于 2024-11-13 10:10:23 字数 925 浏览 1 评论 0原文

请解释以下行为。

class Base
{
    public int num = 3;

    public int getNum()
    {
        return num;
    }

    public void setNum(int num)
    {
        this.num = num;
    }
}


class child
    extends Base
{
    public int num = 4;

    public child()
    {

    }

    public child(int i)
    {
        this.num = i;
    }

    public int getNum()
    {
        return num;
    }

    public void setNum(int num)
    {
        this.num = num;
    }
}

public class Main
{

   public static void main(String[] args)
   {

        Base obj2 = new child();
        System.out.println(obj2.num);
        System.out.println(obj2.getNum());

        Base obj3 = new child(10);
        System.out.println(obj3.num);
        System.out.println(obj3.getNum());
    }
}

输出 : 3 4 3 10

这里 obj2.num 和 obj3.num 仍然指向 Base 类实例变量中分配的值 3。它不会像 obj2.getNum() 和 obj3.getNum() 一样被覆盖吗?

提前致谢。

Please explain the following behaviour.

class Base
{
    public int num = 3;

    public int getNum()
    {
        return num;
    }

    public void setNum(int num)
    {
        this.num = num;
    }
}


class child
    extends Base
{
    public int num = 4;

    public child()
    {

    }

    public child(int i)
    {
        this.num = i;
    }

    public int getNum()
    {
        return num;
    }

    public void setNum(int num)
    {
        this.num = num;
    }
}

public class Main
{

   public static void main(String[] args)
   {

        Base obj2 = new child();
        System.out.println(obj2.num);
        System.out.println(obj2.getNum());

        Base obj3 = new child(10);
        System.out.println(obj3.num);
        System.out.println(obj3.getNum());
    }
}

Output :
3
4
3
10

Here how obj2.num and obj3.num still point to the value 3 which is assigned in the Base class instance variable. Wont it get overidded like the obj2.getNum() and obj3.getNum().

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

内心荒芜 2024-11-20 10:10:23

由于对象是用超类类​​型声明的,因此您将获得超级成员变量值。

如果对象是用子类类型声明的,则该值将被覆盖值。

如果将 Base obj3 = new child(10); 修改为 child obj3 = new child(10); 则输出将为 3 4 10 10代码>

这里有很好的解释

Because the objects are declared with super class type, you get the super member variable value.

If the object was declared with sub class type, the value would be overridden value.

If the Base obj3 = new child(10); is modified to child obj3 = new child(10); the output would be 3 4 10 10

This is well explained here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文