开发者

Static members in Java [duplicate]

开发者 https://www.devze.com 2022-12-18 16:16 出处:网络
This question already has answers here: Are static methods inherited in Java? (15 answers) Closed 4 years ago.
This question already has answers here: Are static methods inherited in Java? (15 answers) Closed 4 years ago.

I've read Statics in Java are not inherited. I've a small program below which compil开发者_高级运维es and produces 2 2 as output when run. From the program it looks like k (a static variable) is being inherited !! What am I doing wrong?

class Super
{
    int i =1;
    static int k = 2;
    public static void print()
    {
        System.out.println(k);
    }
}
class Sub extends Super
{
    public void show()
    {
        // I was expecting compile error here. But it works !!
        System.out.println(" k : " + k);
    }
    public static void main(String []args)
    {
        Sub m =new Sub();
        m.show();
        print();
    }
} 


The scope in which names are looked up in includes the super class.

The name print is not found in Sub so is resolved in the Super.

When the compiler generates bytecode, the call will be made to Super.print, rather than a call on a method in Sub.

Similarly the k is visible in the sub-class without qualifying it.


There is no polymorphism here, only inheritance of the contents of a name space. Static methods and all fields do not have polymorphic dispatch in Java, so can only be hidden by sub-classes, not overridden. The post you link to in your comments is using 'inheritance' in a somewhat unconventional way, mixing it up with polymorphism. You can have polymorphism without inheritance and inheritance without polymorphism.


Sub extends Super so it can see all the public/protected/package (static) members of Super.

I guess this is what you described as "Statics in Java are not inherited" change

static int k = 2;

to

private static int k = 2;

and your Sub program won't see 'k' anymore and won't compile;

also try to create a new 'static int k=3;' in Sub, and see what happens.


It's pretty much the same as accessing Math.PI or any other global constant (which also have public and final modifiers).

In your case you have default (package) scope.

It's independed of inheritance only the scope restricts whether it is visible.


I think you might be wrong about static variables not being inherited. I suppose some properties of it are not inherited. For instance a static var normally means that all instances of the class have access to the same place in memory.

When you inherit, the derived class does not refer to the same memory as the base class.


Static member can be static data member and static method which can be accessed without using the object. It is used by nested class

0

精彩评论

暂无评论...
验证码 换一张
取 消