Java中的抽象类不需要从其实现接口实现任何方法。为什么?
让我们看一下以下Java中的简单代码片段Java中的抽象类不需要从其实现接口实现任何方法。为什么?,java,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) {
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()代码>。然而,编译器一点也不抱怨,程序运行良好,没有任何问题。为什么?
类似地,非抽象的final类Calculation正在实现Mul接口,并包含方法showMul()的实际实现代码>显示在它的实现界面中。在这种情况下,如果类计算中的方法showMul()
被注释,则会发出编译时错误。为什么同样的东西不适用于抽象类Super?,因为它是抽象的。抽象类是允许声明某些方法的类,而不提供这些方法的任何实现,强制具体的子类这样做。您可以添加该方法
@Override
public abstract void showSum();
对于抽象类,它只是与接口中已声明的方法冗余。在这种情况下,抽象类的行为类似于接口
从:…抽象类类似于接口,只是它们提供了部分实现,将其留给子类来完成实现。如果抽象类只包含抽象方法声明,则应将其声明为接口
您不会在扩展另一个接口的接口中实现方法。您不必在实现接口的抽象类中实现方法。抽象类不是真正的实现类。它可能包含abstract
方法,并且不需要从接口实现方法。真正的实现类关心的是定义抽象/接口方法
看到抽象类和接口之间的区别了吗
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
}
这里是real类,它扩展了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
上没有编译时错误:
我们不能创建抽象类的实例。这就是为什么在编译时显示错误没有任何意义。这应该是对JB Nizet答案的评论,但我还不能发表评论:(
请注意,您可以在抽象类中提供showSum()方法的实现,并且仍然使该类保持抽象而没有任何问题。抽象类可以实现所有方法,并且仍然是抽象的!来自Oracle的Java教程:
实现接口的类必须实现所有
但是,可以定义一个
如果
类被声明为抽象类
参考文档:,抽象类实现接口时的节