Java中的多继承

多继承是指一个类继承多个类的特性。Java中一般情况之下都只支持单继承,因为单继承是有单继承的好处的,安全性比较高,所以在Java中单继承的使用时比较多的,或者说除了必须使用多继承以外都得使用单继承。但是多继承也是必须有的,接口和内部类就提供了多继承的思想。

【1】接口

抽象类中子类只能继承一个父类,但是却可以实现多个接口。为什么接口可以多继承的原因是在接口中没有任何具体的方法的实现,所以不会存在冲突的问题。

package TwoWeek;
// 接口的方式实现多继承
public class MulTest1 {
	public static void main(String args[]){
		Son son = new Son();
		son.eat();              // 儿子吃饭
		son.strong();		// 我很强壮
		son.beautiful();	// 我很漂亮
		son.fight();		// 会打架
	}
	
}
// 父亲接口
interface Father{
	void strong();
	void fight();
}
// 母亲接口
interface Mother{
	void beautiful();
}

class Character{
	public void eat(){
		// 这个函数可以在下面被覆写
		System.out.println("吃饭");
	}
	public void fight(){
		// 这个方法父类实现了,子类就不需要实现了
		System.out.println("会打架");
	}
}

// 实现了多继承同时也是继承喝接口的联合使用
class Son extends Character implements Father, Mother{
	public void eat(){
		// 可以覆写上边的方法
		System.out.println("儿子吃饭");
	}
	public void strong(){
		System.out.println("我很强壮");
	}
	public void beautiful(){
		System.out.println("我很漂亮");
	}

【2】内部类

使用接口的方式固然很好,但是其是具有局限性的。如果我已经定义好了一些抽象类或者具体类,不想将其转变成接口,那只能是采用内部类的方式了实现了。其实内部类的实现方式也很强大。

package TwoWeek;
// 使用内部类的方式实现多继承
public class MulTest2 {
	public static void main(String args[]){
		Son2 son = new Son2();
		System.out.println(son.getStrong());
		System.out.println(son.getBeautiful());
	}
}

class Father2 {  
    public int strong(){  
        return 9;  
    }    
}  
  
class Mother2 {  
    public int beautiful(){  
        return 8;  
    }  
}  
class Son2{
	class FatherInner extends Father2{
		public int strong(){
			return super.strong()+1;
		}
	}
	// 在继承的基础之上加上自己的属性
	class MotherInner extends Mother2{
		public int beautiful(){
			return super.beautiful()+1;
		}
	}
	
	public int getStrong(){
		return new FatherInner().strong();
	}
	
	public int getBeautiful(){
		return new MotherInner().beautiful();
	}
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值