微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java中的抽象类不需要从其实现接口中实现任何方法.为什么?

我们来看看下面的 Java代码片段.
interface Sum
{
    abstract public void showSum();
}

interface Mul
{
    abstract public void showMul();
}

abstract class Super implements Sum
{
    protected int x;
    protected int y;

    public Super(int x,int y)
    {
        this.x=x;
        this.y=y;
    }

    //No error,though the method showSum() of the implementing iterface Sum is commented. Why?

    /*public void showSum()
    {
        System.out.println("Sum = "+(x+y));
    }*/
}

final class Calculation extends Super implements Mul
{
    public Calculation(int x,int y)
    {
        super(x,y);
    }

    public void showSum()
    {
        System.out.println("Summation = "+(x+y));
    }

    //If showMul() is commented,it would issue a compile-time error. Why?
    public void showMul()
    {
        System.out.println("Multiplication = "+(x*y));
    }   
}

final public class Main
{
    public static void main(String[] args) throws IOException
    {
        Scanner s=new Scanner(system.in);

        System.out.print("\nEnter a number : ");
        int x=s.nextInt();

        System.out.print("\nEnter another number : ");
        int y=s.nextInt();

        Calculation c=new Calculation(x,y);
        c.showSum();
        c.showMul();
    }
}

由于接口Sum只包含一个方法showSum();正在由抽象类Super实现,应该有必要对抽象类Super来实现该方法showSum();.编译器根本就没有抱怨,程序运行良好,根本没有问题.为什么?

类似地,非抽象最终类Calculate正在实现Mul接口,并包含方法showMul()的实际实现;在其实现界面中呈现.在这种情况下,如果该方法在类Calculate中显示Mul(),则会发出编译时错误.为什么同样的事情不适用于那个抽象类Super?

解决方法

抽象类不是真正的实现类.它可能包含抽象方法,并且不需要从接口实现方法. REAL实现类的关注是定义抽象/接口方法.

看到抽象类和接口之间的区别

Interface:
public interface InterfaceClass {
    void interfaceMethod();
    //no method deFinition
}


//Abstract Class implementing InterfaceClass
abstract class AbsClass implements InterfaceClass{
    abstract void abstractMethod();
    public void doSomethingCommon() {
        System.out.println("Abstract class may contain method deFinition");
    }
    //no need to implement methods of InterfaceClass because AbsClass is abstract
}

而这里是扩展AbsClass的真正类:它的RealClass的义务来定义所有的抽象方法和接口方法.另外,它也可以覆盖抽象类中定义的方法.

public class RealClass extends AbsClass{
    @Override
    public void interfaceMethod() {
        //implement interface method here
    }
    @Override
    void abstractMethod() {
    }
    // you may override the doSomethingCommon() of AbsClass too
    @Override
    public void doSomethingCommon() {
        // Todo Auto-generated method stub
        super.doSomethingCommon();
    }
}

为什么AbsClass上没有编译时错误:我们不能创建抽象类的实例.这就是为什么在编译时没有显示错误的意义.

原文地址:https://www.jb51.cc/java/125312.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐