×
☰ See All Chapters

Java abstract class vs. interface       

In this chapter you learn the differences between java abstract class and interface.

Abstract Class

Interface

Abstract class can contain the following members:

  1. Instance and static variables 

  2. Instance and static block 

  3. Concrete methods (Instance and static) 

  4. Abstract methods 

  5. Constructor 

An interface can contain the following members:

  1. public static final variables 

  2. public abstract methods 

Abstract method inside abstract class should have abstract keyword.

abstract class A {

        abstract int add(int a, int b);

}

Abstract method inside interface is not necessary to have abstract keyword. Compile will add abstract keyword to all methods of interface.

interface A {

        int add(int a, int b);

}

Implementation class has to extend abstract class using “extends” keyword.

abstract class A {

        abstract int add(int a, int b);

}

class B extends A {

        int add(int a, int b) {

                return a + b;

        }

}

Implementation class has to implement an interface using "implements” keyword.

interface A {

        int add(int a, int b);

}

class B implements A {

        public int add(int a, int b) {

                return a + b;

        }

}

Implementation class can extend only one abstract class.

abstract class A {

        abstract int add(int a, int b);

}

class B extends A {

        int add(int a, int b) {

                return a + b;

        }

}

 

Implementation class can implement any number of interfaces.

interface A {

        int add(int a, int b);

}

interface B {

        int subtract (int a, int b);

}

class C implements A, B {

        public int add(int a, int b) {

                return a + b;

        }

        public int subtract(int a, int b) {

                return a - b;

        }

}

It is used for doing partial implementation; It can have complete or partial implementation. Abstract class can have both abstract and concrete methods.

It is completely specification, has zero percent implementation. Interface can have only abstract methods.

It supports abstraction to a smaller extent. Can be 100% abstraction if all the methods in it are abstract methods.

It supports 100% abstraction.

Multiple inheritance cannot be achieved using abstract class.

Using interface you can achieve multiple inheritance.

Abstract class can implement interface.

Interface cannot implement anything.

An abstract class can extend another Java class and implement multiple Java interfaces.

Interface can extend another interface.


All Chapters
Author