Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Predict Output of the CODE:

 
anshul gupta
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A {
String s1 = "A.s1"; String s2 = "A.s2";
void t1(){
System.out.println("IN CLASS A");
}
}
class B extends A {
String s1 = "B.s1";
String s2 = "B.s2";
//String s12 = "B.s12";
void t1(){
System.out.println("IN CLASS B");
System.out.print(super.s1);
}
public static void main(String args[]) {
B x = new B(); A y = (A)x;
A z = new B();
System.out.println(x.s1+" "+x.s2+" "+y.s1+" "+y.s2);
System.out.println(z.s1+" "+z.s2);
z.t1();
}
}

output:

this might be silly but please figure out what will be the output of the given code snippet...and please explain it.
thanks in advance.
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is not fair to ask us to run the code, when you should be able to do it yourself.

Run the code and look at the output, then see if you have any questions for us. I'm moving this to the beginners forum.

Dave
 
Sen George
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I ran the program and here is the output.

B.s1 B.s2 A.s1 A.s2
A.s1 A.s2

In CLASS B
A.s1


Here is the explanation.

The first line of output is straight-forward. It just prints the values of the respective instance variables.
In the second line of output, the instance variables of the referenced class (in this case-class A) is printed. The instance variables of class B won't be printed as overriding does not kick in (overriding applies only to instance methods).
The third and the fourth lines of output are generated as a result of the call to the method t1 of class B-B.t1() overrides A.t1().

Trust this clarifies.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic