我们来看看下面的
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(); } }