类继承几点常见注意事项

先看父类、子类代码:
public class FatherClass {
	public FatherClass(){
		System.out.println("father constructor");
	}
	
	protected void father1(){
		System.out.println("father1");
	}
}
public class SonClass extends FatherClass {


	public SonClass() {
		System.out.println("son constructor");
	}
	
	protected void father1(){
		System.out.println("father1 son");
	}


	protected void son1(){
		System.out.println("son1");
	}
}


几点注意事项:

1、执行子类的构造函数前会先执行父类的构造函数;
SonClass sonclass =  new SonClass();
输出:
father constructor
son constructor


2、子类可以重写父类的方法,重写的方法请注意:

比如SonClassc重写了FatherClass的father1(),通过子类对象调用father1()时,只执行子类的father1(),不执行父类的father1();        
SonClass sonclass =  new SonClass();
sonclass.father1();
输出:
father constructor
son constructor
father1 son        


3、声明为子类、实例化为父类:
SonClass sonclass = new FatherClass(); 	//错误,要强制转换,像下面那样:
SonClass sonclass = (SonClass) new FatherClass();
但是这样会报错,因为一个父类可以有很多个子类,不能讲父类强制转换为某一个子类:

4、声明为父类、实例化为子类:
FatherClass sonclass =  new SonClass();
sonclass.father1();
sonclass.son1();  //报错,没有该函数
仍只执行子类的函数,并且子类中独有的函数还不能调用了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值