为什么Java不支持动态变量分配 [英] why java does not support dynamic variable dispatch

查看:59
本文介绍了为什么Java不支持动态变量分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果标题错误,请原谅.有两个类Test和TestChild1,其中TestChild1是从Test继承的.这两个类都有一个名为"a"的变量.当我尝试通过用子类对象实例化的超类变量访问变量"a"时,它给出的是在超类而不是子类中初始化的值. 以下是引起怀疑的代码

Please excuse me if title is wrong. There are two class Test and TestChild1 where TestChild1 is inherited from Test. Both classes have a variable named "a". When I tried to access variable "a" through superclass variable which is instantiated with subclass object, it is giving the value that is initialized with in superclass not subclass. following is the code that raised the doubt

class Test {
    public int a = 10;
}

class TestChild1 extends Test {
    public int a = 20;
}

class Main {
    public static void main(String args[]) {
        Test test = new TestChild1();
        System.out.println(test.a); // results in 10
    }
}

请告诉我这种行为的原因.预先感谢....

Please give me the reasons for this behavior. Thanks in advance....

推荐答案

因为Java设计人员决定使方法变为多态的(因此是可重写的),而不是字段.

Because the Java designers decided to make methods polymorphic (and thus overridable), but not fields.

当您引用对象中的字段时,编译器会根据变量的声明的类型决定要使用的字段,在这种情况下, Test.

When you reference a field from an object, the compiler decides which field to use, based on the declared type of the variable, which, in this case, is Test.

当您引用方法时,JVM在运行时根据对象的实际,具体类型(在本例中为TestChild)选择要调用的方法.

When you refer to methods, the JVM, at runtime, chooses which method to call based on the actual, concrete type of the object which, in this case, is TestChild.

OO完全是关于状态的封装,因此无论如何您几乎都不应将字段暴露给外部.

OO is all about encapsulation of state, so you should almost never expose fields to the outside anyway.

这篇关于为什么Java不支持动态变量分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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