开发者

inheritance n static variables

开发者 https://www.devze.com 2022-12-20 01:14 出处:网络
Is static variable of superclass avilable to sub-class. i.e i mean 开发者_Go百科static variable of superclass can we access in sub-class without creating objectN without using ClassName.The same visib

Is static variable of superclass avilable to sub-class. i.e i mean 开发者_Go百科static variable of superclass can we access in sub-class without creating object N without using ClassName.


The same visibility constraints apply to static and non-static variables. So this is possible:

public class SuperClass {
    /*
     * public would also work, as would no modifier 
     * if both classes are in the same package
     */
    protected static String foo;
}

public class SubClass extends SuperClass {
    public void modifyFoo() {
        foo = "hello";
    }

    public void modifySuperFoo() {
        /*
         * does the exact same thing as modifyFoo()
         */
        SuperClass.foo = "hello";
    }
}


In super class:

public static int staticVarName = 42;

In sub-class:

System.out.println("value: " + ClassName.staticVarName);


The whole point of static variables/methods is that you can access them without creating an instance of the class.

0

精彩评论

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

关注公众号