aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Super class?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Super class??" Watch "Super class??" New topic
Author

Super class??

sonir shah
Ranch Hand

Joined: Nov 01, 2001
Posts: 435
Question ID :953582008890
What will be the result of attempting to compile and run the following code?
public class Nesting
{
public static void main(String args[])
{
B.C obj = new B( ).new C( );
}
}
class A
{
char c;
A(char c) { this.c = c; }
}
class B extends A
{
char c = 'a';
B( ) { super('b'); }
class C extends A
{
char c = 'c';
C( )
{
super('d');
System.out.println(B.this.c);
System.out.println(C.this.c);
System.out.println(super.c);
}
}
}
Options :
1)It will not compile
2)It will give Runtime error
3) The program will compile without error and print a,c and d in that order when run
4) The program will compile without error and print a,b and d in that order when run
5) The program will compile without error and print b, c and a in that order when run
Ans :3)
I tried running the program, it gave me answer 3).
but i cant understand such an output.Can anyone explain me ??
Sonir
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Sonir
I reposted the code below and added some commnets to it so you can follow what is going on.

The first thing that happens is in main it creates a B.C object. To do this the 1st thing it has to do is create a B object at line **1. In that constructor it calls the superclas constructor (line **2) and passes it the char 'b'. the cosntructor for the A object assigns the value it gets passed to its member variable c. So at this point the variable c in class A has the value 'b'.
After the B object is created then the C object can be created - so its constructor (line **3) is called. the first thing it does is call its super class' constructor ((line **2 again) and pass it the value 'd'. So after the constructor for the A object executes the c variable now has the value of 'd'.
The classes B and C also have member variables named c. Their value is never changed in the progrma and when the balance of the constructor for C executes their values are printed.
If your having trouble with the notation check out the inner class campfire story.
Or the Java tutorial
hope that helps you out, if not post what it is your still unsure of and we'll try to clear it up.


Dave
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Super class??