How are variables overridden

牧云@^-^@ 提交于 2019-12-11 06:45:00

问题


package com.mycompany.myproject.mypkg;

interface MyInterface {
    public static final int k = 9;
}

class MyClass implements MyInterface {
    // int k = 89;
}

public class SampleThree extends MyClass {
    static int k = 90;

    public static void main(String args[]) {
        MyClass object = new SampleThree();
        System.out.println(object.k);
    }
}

Why does the above program print '9' instead of '90'?

How are static and member variables overridden in Java?


回答1:


Because fields do not support polymorphism. MyClass.k is 9 (and object is of refered to by MyClass). SampleThree.k would give you 90. Each class has its own set of variables.

(Btw, An IDE would give you a warning here that you are accessing a static variable by an instance, rather than by its class.)




回答2:


Because inheritance is intended to modify behaviour. Behaviour is exposed through methods and those methods can be overridden .

What you can do is to overload a field , not override . For that you need to define that variable outside the Interface in order to give them different values .




回答3:


You are creating Reference Variable of MyClass. So if using this variable you will access k then it will show variable of interface. If you want to access variable having value 90 make reference variable of SampleThree class.




回答4:


You have a static variable k in interface MyInterface. You have implement this interface in class MyClass, then MyClass.k should be 9.

Object is refered to by MyClass. SampleThree.k would give you 90.

Or simply:

Static variable can not be override.

Rules for Overriding static and instance variable & methods:

  1. A compilation error occurs if an instance method overrides a static method.
  2. A compilation error occurs if a static method hides an instance method.
  3. It's permissible for a static variable to hide an instance variable.
  4. It's also permissible for an instance variable to hide a static variable.



回答5:


Overriding concept is not applicable to variables(hence overriding rules). The value is always based on reference type but not based on the run time object.

That's why your program is printing 9 because the reference type of object is MyClass, and MyClass inherited k whose value is 9.The behavior is same irrespective of the static modifier(k ).If you uncomment the line in MyClass the output is always 89.



来源:https://stackoverflow.com/questions/8983002/how-are-variables-overridden

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!