First of all we will talk about static variables. Remember! There is only one static variable for the whole class and all its subclasses and their instances! The following example illustrates it:
class T1 {
static int a = 5;
}
class T2 extends T1 { }
public class Sfield {
public static void main(String[] args) {
T2.a = 6;
System.out.println(T1.a);
System.out.println(T2.a);
}
}
And the output is:
6What would happen though, if in T2 we define again the static int a? Let's have a look:
6
(Luckily there is no third 6 since it could have got scary)
class T1 {
static int a = 5;
}
class T2 extends T1 {
static int a = 6;
}
public class Sfield {
public static void main(String[] args) {
System.out.println(T1.a);
System.out.println(T2.a);
}
}
And the output of this will be:
5So now apparently we have different static fields for each class and its instances. What does matter here, is the type of the reference variable that we try to access the member.
6
The similar thing happens with static methods. It is important to remember that static methods can not be overridden. We can though, redefine them!
class R1 {
static void say() {
System.out.println("R1");
}
}
class R2 extends R1 {
static void say() {
System.out.println("R2");
}
}
public class Sfield {
public static void main(String[] args) {
R1.say();
R2.say();
}
}
And the output will be:
R1But still it's not an override but a redefinition!
R2
No comments:
Post a Comment