Is static variable of superclass avilable to sub-class. i.e i mean static variable of superclass can we access in sub-class without creating object N without using ClassName.
+2
A:
In super class:
public static int staticVarName = 42;
In sub-class:
System.out.println("value: " + ClassName.staticVarName);
tur1ng
2010-02-11 09:41:23
+3
A:
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";
}
}
Thomas Lötzer
2010-02-11 09:41:57
but then you could not access SuperClass.foo.
Vinay Pandey
2010-02-11 09:51:29
@vinay_rockinYes, you can. You can also write `SuperClass.foo = "hello";` instead of `foo = "hello";` and it will achieve the exact same result.
Thomas Lötzer
2010-02-11 09:54:04
@Thoma, please see my edited answere and let me know if it is incorrect.
Vinay Pandey
2010-02-11 10:01:36
@Thomas Lotzer, I am using c# and it does not work for me as I cannot access protected static variable by ClassName.variable. but I will take it as you say and read more on internet :).
Vinay Pandey
2010-02-11 10:24:26
@vinay_rockin The question is about Java, so my answer is also about Java. C# may behave differently in this case.
Thomas Lötzer
2010-02-11 10:26:21
+1
A:
The whole point of static variables/methods is that you can access them without creating an instance of the class.
er4z0r
2010-02-11 09:43:18