Sunday, August 15, 2010

Static modifier.

Hello there! Static modifier is a very wide subject and obviously I'm not going to explain everything now. But you will find here a couple of interesting notes!

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:
6
6
(Luckily there is no third 6 since it could have got scary)
What would happen though, if in T2 we define again the static int a? Let's have a look:
 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:
5
6
So 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.

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:
R1
R2
But still it's not an override but a redefinition!

No comments:

Post a Comment