首页 > 解决方案 > Multiple Inheritance using Anonymous class in Java

问题描述

I know that multiple inheritance is not supported in java. I wrote the code as shown below.

abstract class abc {
    public abstract void print();
}

abstract class xyz {
    public abstract void print();
}

public class Test {

    public static void main(String[] args) {
        abc obj1 = new abc() {
            public void print() {
                System.out.println("abc");
            }
        };

        xyz obj2 = new xyz() {
            public void print() {
                System.out.println("xyz");
            }
        };

        obj1.print();
        obj2.print();       
    }
}

The output produced is:

abc
xyz

My question is, here I am using two abstract classes with a concrete class. Isn't that an implementation of multiple inheritance? And I intend to implement the code using classes, not interfaces.

标签: javaanonymous-class

解决方案


我正在使用两个抽象类和一个具体类。这不是多重继承的实现吗?

不,您正在main方法中创建两个匿名类的实例。Test该类与创建的两个匿名类实例中的任何一个之间没有继承关系。

abc类与扩展它的匿名类之间存在单一继承关系。

xyz在类和扩展它的匿名类之间还有另一个单一的继承关系。


推荐阅读