Java多重继承的两种方式
程序员文章站
2022-07-15 17:06:23
...
参考网址: https://www.cnblogs.com/chenssy/p/3389027.html
1.使用接口
public class Superhero extends ActionCharacter implements FlyAbility,SwimAbility{
@Override
void fight() {
System.out.print("会打架");
}
@Override
public void canFly() {
System.out.print("会飞");
}
@Override
public void canSwim() {
System.out.print("会游泳");
}
}
abstract class ActionCharacter{
abstract void fight();
}
interface FlyAbility{
void canFly();
}
interface SwimAbility{
void canSwim();
}
2.使用内部类
/*内部类使的多继承的实现变得更加完美了,同时也明确了如果父类为抽象类或者具体类,那么我就仅能通过内部类来实现多重继承了。*/
public class UseInnerClassHandleMultiExtendsTest {
public static void main(String[] args) {
Son son = new Son();
Son.LikeMother motherLike = son.getKind();
motherLike.display();
Son.LikeFather fatherLike = son.getStrong();
fatherLike.display();
}
}
/*这里定义了两个内部类,他们分别继承父亲Father类、母亲类Mother类,且都可以非常自然地获取各自父类的行为,
这是内部类一个重要的特性:内部类可以继承一个与外部类无关的类,保证了内部类的独立性,正是基于这一点,多重继承才会成为可能。*/
class Father{
public void getStrong(){
System.out.println("像父亲一样强壮");
}
}
class Mother{
public void getKind(){
System.out.println("像母亲一样和蔼");
}
}
class Son{
class LikeMother extends Mother{
public void display(){
getKind();
}
}
class LikeFather extends Father{
public void display(){
getStrong();
}
}
LikeFather getStrong(){
return new LikeFather();
}
LikeMother getKind(){
return new LikeMother();
}
}