Don
Don

Reputation: 1458

Do Abstract classes need to implement an entire interface in java 7?

I need a group of different classes to implement a certain interface. However, a lot of those classes, but not all of them, need a same implementation for some of the methodes defined in the interface. I was wondering if I could make an abstract class implement the interface and only create the methods that are the same for those classes?

For example, I have interface A:

public interface A{ public returnType method1(){}; public returnType method2(){}; }

Can I do this:

public abstract class AbstractPartialA implements A{
     @Override
     public returnType method1(){
         implementation
     }
}

and than have the classes extending from this Abstract class implement the remaining methods that are required to fulfill the interface?

Upvotes: 0

Views: 107

Answers (3)

Hello_JAVA
Hello_JAVA

Reputation: 96

Do Abstract classes need to implement an entire interface in java 7?

And the answer is " NO ". Abstract class can implement entire interface or it can implement only some methods of an interface.

Case-1

If it implements entire interface and is still declared as 'abstract', it means we don't want other(people who are going to use our class) to create object for our class

Example of such class is HttpServlet in javax.servlet.http . Here HttpServlet class doesn't have any abstract method, but still it is declared as 'abstract'

Case-2

Simple, if the class doesn't implement any one of the method of an interface, then it is declared as 'abstract'. Now it will be the responsibility of the other class which extends the abstract class to provide the implementation of such method which is not implemented by 'abstract class'

Upvotes: 1

GuilleOjeda
GuilleOjeda

Reputation: 3361

You can, and when you try to extend from AbstractPartialA Java will ask you to:

  • Implement all methods declared in implemented interfaces and not implemented
  • Implement all methods declared as abstract in superclasses

Remember that a class is considered to implement all interfaces implemented by its superclasses, not just the ones specifically written after the implements keyword in this class' declaration. This applies both to the types of the class (and thus the types of its references) and to the methods it is required to implement.

Upvotes: 0

mel3kings
mel3kings

Reputation: 9405

Yes, you can, that is the exact purpose of abstract classes.

Upvotes: 4

Related Questions