This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Predict Output of the CODE: Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Predict Output of the CODE:" Watch "Predict Output of the CODE:" New topic

Predict Output of the CODE:

anshul gupta

Joined: Aug 23, 2007
Posts: 11
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");
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);


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.

excuse me...while i kiss the sky.
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

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.

Sen George
Ranch Hand

Joined: Sep 21, 2005
Posts: 76
I ran the program and here is the output.

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


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.
I agree. Here's the link:
subject: Predict Output of the CODE:
It's not a secret anymore!