-1

Hi I have faced in my SCJP examination this question. If both interface and abstract class having same methods then which one is better to override all methods into my class in java? Please explain me in different scenarios for which one is better to take.

This is interface :

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

This is abstract class :

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

This is my class name: ArithMethodImplemenation class.

Now at what scenario I should do like this

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

or at what scenario I should do like this

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

Please explain me with different scenarios. And my friends also faced this question in so many interviews. But they couldn't succeed.

Venkaiah Yepuri
  • 1,561
  • 3
  • 18
  • 29
  • Is the abstract class completely empty as you stated? You have to choose between writing the class or the interface, or you have both and should decide between implementing the interface or extending the class? – Flavio Oct 10 '13 at 14:49

3 Answers3

2

There is no point in having an empty abstract class with only abstract methods.

Just use an interface instead.

Remember in Java you can extend only one class but can implement multiple interfaces.

anubhava
  • 761,203
  • 64
  • 569
  • 643
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.

Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
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.

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75