另一个抽象类和非抽象类继承抽象类

时间:2014-03-05 04:58:47

标签: java inheritance abstract-class

当抽象类被另一个抽象类和非抽象类扩展时,有什么区别吗?例如,父抽象类同时具有抽象和非抽象方法。当抽象类由抽象类和非抽象类扩展时,实现方法有什么区别吗?

2 个答案:

答案 0 :(得分:1)

如果抽象类由另一个抽象类扩展,那么它不需要实现所有父类方法,但扩展抽象子类的第一个具体类必须实现所有父抽象类方法。

非抽象类必须实现父抽象类方法

答案 1 :(得分:0)

我试图通过代码涵盖几个基本点。请参阅上述方法的评论。

package abstractpkg;

public class Test {
    public static void main(String[] args) {
        C c = new C();    // Compile-time error. C is abstract
        B b = new B();    // OK: B is concrete 
    }
}

abstract class A{
    abstract void methA();
    public void methB(){

    }
}

/**
 * Non-abstract class extending asbtract class.
 * */
class B extends A{
    /*
     * Since it is Non-abstract class, it must provide impl of abstract method because without impl of 
     * method Object of class can't be created.
     * */
    void methA() {

    };

    /*
     * This overriding is optional, since it's impl is already existing in super class.
     * If class B has to give spl impl then B should override this method
     * */
    @Override
    public void methB() {
        // TODO Auto-generated method stub
        super.methB();
    }
}


abstract class C extends A{
    /*
     * Since C is also abstract it may or may not override the method. 
     * */

    /*
     * Overriding and providing impl is optional.
     * */
    @Override
    void methA() {

    }
}