JAVA中子类实例化过程中super和this的使用

用代码直观理解子类实例化过程。

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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值