-1

嗨,我在 SCJP 考试中遇到了这个问题。如果接口和抽象类都具有相同的方法,那么哪一个更好地将所有方法覆盖到我的java类中?请在不同的情况下向我解释哪种情况更好。

这是界面:

interface ArithmeticMethods {
       public abstract void add();
       public abstract void sub();
       public abstract void div();
       public abstract void mul();
   }

这是抽象类:

abstract ArithMethods {
       public abstract void add();
       public abstract void sub();
       public abstract void div();
       public abstract void mul();
   }

这是我的班级名称: ArithMethodImplemenationclass。

现在在什么情况下我应该这样做

public ArithMethodImplemenation implements ArithmeticMethods{
   //override all methods of ArithmeticMethods
}

或者在什么情况下我应该这样做

public ArithMethodImplemenation extends ArithMethods{
   //override all methods of ArithMethods
}

请用不同的场景解释我。我的朋友在很多采访中也面临这个问题。但他们无法成功。

4

3 回答 3

2

有一个abstract只有abstract方法的空类是没有意义的。

只需使用 aninterface代替。

请记住,在 Java 中,您只能扩展一个类,但可以实现多个接口。

于 2013-10-10T14:53:45.237 回答
1

I do not see the point of an abstract class with only abstract methods and no fields.

An abstract class is supposed to help you by implementing parts of common functionality to avoid having to rewrite that common code in implementing classes.

In that case the interface is more appropriate as it only defines the method signatures.

于 2013-10-10T14:51:21.767 回答
1

You should implement because inheritance primarily meant to inherit all methods from the superclass. Implementation provides a framework where you aren't overriding all your empty inherited methods.

According to the Java Programming Language, Second Edition, by Ken Arnold and James Gosling:

Inheritance - create a new class as an extension of another class, primarily for the purpose of code reuse. That is, the derived class inherits the public methods and public data of the base class. Java only allows a class to have one immediate base class, i.e., single class inheritance.

Interface Inheritance - create a new class to implement the methods defined as part of an interface for the purpose of subtyping. That is a class that implements an interface “conforms to” (or is constrained by the type of) the interface. Java supports multiple interface inheritance.

于 2013-10-10T14:52:31.097 回答