File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Predict Output of the CODE:" Watch "Predict Output of the CODE:" New topic
Author

Predict Output of the CODE:

anshul gupta
Greenhorn

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");
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.


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

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.

Dave
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

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Predict Output of the CODE:
 
Similar Threads
Doubt in String class
Inner Thread Classes
compare objects
== with Strings is giving a different result
Doubt in Strings