为什么变量在覆盖时的行为与方法不同? [英] Why variables are not behaving as same as method while Overriding.?

查看:138
本文介绍了为什么变量在覆盖时的行为与方法不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,Overriding是重新定义子类中成员含义的概念。为什么变量在重写java时不像方法那样?

例如:

Generally Overriding is the concept of Re-defining the meaning of the member in the sub class.Why variables are not behaving like methods while Overriding in java ?
For instance:

class Base {

    int a = 10;

    void display() {
        System.out.println("Inside Base :");
    }
}

class Derived extends Base {

    int a = 99;

    @Override
    // method overriding
    void display() {
        System.out.println("Inside Derived :");
    }
}

public class NewClass {

    public static void main(String... a) {
        Derived d = new Derived();
        Base b = d;
        b.display(); // Dynamic method dispatch
        System.out.println("a=" + b.a);
    }
}

由于数据成员 a 是指定的包访问,它也可用于派生类。但通常在使用基类引用调用重写方法时,会调用在派生类中重新定义的方法(动态方法调度)..但对于变量..Why来说它是不一样的。?

Since data member a is package access specified, it is also available to the Derived class. But generally while calling the overridden method using the base class reference, the method that is redefined in derived class is called (Dynamic method dispatch)..but it is not the same for the variable..why.?

预期输出

内部衍生:

a = 99

Inside Derived :
a=99

获得的输出:

内部衍生:

a = 10

Inside Derived :
a=10

打印10 - 为什么变量的行为与派生类中的方法不相似?

为什么不允许在子类中重写变量?

Prints 10 - why the variable does not behave similar to method in the derived class?
Why the variables are not allowed to be overridden in the sub class?

推荐答案

您输入 b 作为 Base 的实例。因此,当编译器需要解析 ba 时,它会查找 Base 的定义,以表示<$ c $的含义C> BA 。实例字段没有多态性。

You typed b as an instance of Base. So when the compiler needs to resolve b.a, it looks to the definition of Base for the meaning of b.a. There is no polymorphism for instance fields.

这篇关于为什么变量在覆盖时的行为与方法不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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