Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What (not) to declare when implementing an interface with an abstract class?

Tags:

People also ask

What happens if an abstract class implements an interface?

Java Abstract class can implement interfaces without even providing the implementation of interface methods. Java Abstract class is used to provide common method implementation to all the subclasses or to provide default implementation. We can run abstract class in java like any other class if it has main() method.

What are the components that are not allowed in interface and abstract class?

An interface thus cannot contain constants, fields, operators, constructors, destructors, static constructors, or types. Also an interface cannot contain static members of any kind.

What can an abstract class do that an interface Cannot?

An abstract class permits you to make functionality that subclasses can implement or override whereas an interface only permits you to state functionality but not to implement it. A class can extend only one abstract class while a class can implement multiple interfaces.

Can we declare abstract class in interface?

Implementation: Abstract class can provide the implementation of the interface. Interface can't provide the implementation of an abstract class. Inheritance vs Abstraction: A Java interface can be implemented using the keyword “implements” and an abstract class can be extended using the keyword “extends”.


I have an interface A, for which I have to supply a few different implementations. However, those implementations share some helper methods, so I moved those methods to an abstract base class.

Interface A {
    void doX();
}

abstract Class B implements A {
    protected void commonY() {
        // ...
    }

    @Override
    public abstract void doX();
}

Class C extends B {
    @Override
    public void doX() {
        // ...
    }
}

Class D extends B {
    @Override
    public void doX() {
        // ...
    }
}

My code works as expected, but I have a few questions:

  • Should I declare the abstract Method doX() in Class B? Why (not)?

  • Should I also explicitly declare "implements A" on Class C and D? Why (not)?