Java中的多继承

来源:互联网 发布:php serialize json 编辑:程序博客网 时间:2024/06/18 17:09

多继承是指一个类继承多个类的特性。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 0