R
rnurse
Hi All,
I'm confused by this code snippet:
class Base
{
String s = "BaseStr";
void print( )
{
System.out.println("Super " + s);
}
Base( )
{
print( );
}
}
public class Derived extends Base
{
String s = "DerivedStr";
void print( )
{
System.out.println("Sub " + s);
}
Derived( )
{
}
public static void main(String [] args)
{
Base b = (Base) new Derived( );
}
}
What I'm thinking should happen is that when the Derived constructor,
Derived(), is called, a call to super() is made. This call then leads
to the no-arg constructor of it's parent class Base: Base(). Base()
calls super() which is the no-arg constructor of its parent Object:
Object( ). Object( ) completes and then control is passed to Base( )
which should then call its print( ) method and print out "Super
BaseStr". After Base( ) runs Derive( ) completes. Therefore the
output should be "Super BaseStr". Yet, the output is "Sub null". What
gives? And, why is s = null at this point. Should s have been
initialized to "DerivedStr" by now?
I'm confused by this code snippet:
class Base
{
String s = "BaseStr";
void print( )
{
System.out.println("Super " + s);
}
Base( )
{
print( );
}
}
public class Derived extends Base
{
String s = "DerivedStr";
void print( )
{
System.out.println("Sub " + s);
}
Derived( )
{
}
public static void main(String [] args)
{
Base b = (Base) new Derived( );
}
}
What I'm thinking should happen is that when the Derived constructor,
Derived(), is called, a call to super() is made. This call then leads
to the no-arg constructor of it's parent class Base: Base(). Base()
calls super() which is the no-arg constructor of its parent Object:
Object( ). Object( ) completes and then control is passed to Base( )
which should then call its print( ) method and print out "Super
BaseStr". After Base( ) runs Derive( ) completes. Therefore the
output should be "Super BaseStr". Yet, the output is "Sub null". What
gives? And, why is s = null at this point. Should s have been
initialized to "DerivedStr" by now?