This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Object orientation  RSS feed

 
harish shankarnarayan
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Raj Man
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();}
}
 
Rajesh MadhanGopal
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Pls clarify...
 
ak pillai
author
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!