interface I {String s1 = "I";} class A implements I {String s1 = "A";} class B extends A {String s1 = "B";} class C extends B { String s1 = "C"; void printIt() {
\\ 1 System.out.print(((A)this).s1 + ((B)this).s1 + ((C)this).s1 + ((I)this).s1); } public static void main (String[] args) {new C().printIt();} }
can anyone explain wats happening in line 1 step by step how the parenthesis gets evaluated at line 1 and the output
In each of class ie A, B and C definition, you are defining same member variable. When you assign member variable at each class level, it's only reflected at that class level member variable and does not change value at super level.
When you print values with narrow typecasting, there is a value available for s1 at each narrowed scope of object, which is printed (ABCI). Assume that you do not have values defined at B and C level, the output would be "AAAI" (refer code below). It's good question I would say.
interface I {String s1 = "I";} class A implements I {String s1 = "A";} class B extends A {} class C extends B {
void printIt() {
System.out.print(((A)this).s1 + ((B)this).s1 + ((C)this).s1 + ((I)this).s1); } public static void main (String[] args) {new C().printIt();} }
I thought all variables declared in an interface are public static final (as said in K&B scjp 5 exam guide pg23)and that its value cannot be reset by a class which implements it. The example mentioned here seems to prove my assumption wrong.
The interface member variable by defaulty public,static,final.
It is public because it has to access out side the interface. It is final because the value never changes It is static because you can never have an instance of an interface (that isn't an instance of a class). Where would the instance variable live?