A quick Java puzzle

OK, no peeking…

Say I have a class A and a class B:

public class A {
	protected static Integer value = 5;
 
	public static Integer getValue() {
		return value;
	}	
}
 
public class B extends A {	
	public static void changeValue() {
		value++;
	}
}
 
public class Test {
	public static void main(String argv[]) {		
		System.out.println(A.getValue());
		System.out.println(B.getValue());
 
		B.changeValue();
 
		System.out.println(A.getValue());
		System.out.println(B.getValue())
	}	
}

Now… what does this print?

My personal guess would have been:

5
5
5
6

It itsn’t though. It’s:

5
5
6
6

Apparently subclasses don’t get their own copy of inherited static fields… go figure. After 12 years of Java I’m still learning new things.

Leave a Reply

  • Google ads