用代码直观理解子类实例化过程。
1、注意其中super和this关键字的使用。
2、分别对第7,8,9行代码进行注释后运行,观察运行结果。
3、对第45行代码进行取消注释,观察运行结果。
4、注意第51行和第52行代码中this关键字的不同使用方式。
5、源代码不动,注释掉父类中Father()构造方法(第22~25行代码),观察运行结果,并看父类构造函数的注释语句。
class ExtendsDemo
{
public static void main( String[] args )
{
Son s = new Son();
//Son s1 = new Son( 110 );
//Son s2 = new Son( 1, 2 );
//s.speak();
}//end of method main
}//end of class ExtendsDemo
class Father
{
String name;
int age;
Father( ) //此构造函数可以被子类隐式调用
{
System.out.println( "Father( ) is run" );
}//end of method Father
Father( int x )//如果只有此构造函数,在子类中只能手动调用
{
System.out.println( "Father( int x ) is run:" );
}//end of method Father
void speak()
{
System.out.println( "I am father!" );
}//end of method speak
}//end of class Father
class Son extends Father
{
Son()
{
//super( 2116 );
System.out.println( "Son() is run" );
}//end of method Son
Son( int x )
{
this();
this.speak();//该句在此为打酱油,为表示this调用构造方法和一般方法的不同语法
System.out.println( "Son( int x ) is run" );
}//end of method Son
Son( int x, int y )
{
this( x );
System.out.println( "on( int x, int y ) is run" );
}//end of method Son
void speak()
{
System.out.println( "I am Son!" );
}//end of method speak
}//end of class Son