1.7K
Difference between abstract class and interface
Table of Contents
In this article you’ll come to know about Difference between abstract class and interface in Java.
Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can’t be instantiated.
Difference between abstract class and interface
But there are many differences between abstract class and interface that are given below.
Abstract class | Interface | |
1 | An abstract class can extend only one class or one abstract class at a time. | An interface can extend any number of interfaces at a time |
2 | An abstract class can have abstract and non-abstract class | An interface can only extend another interface |
3 | An abstract class can have abstract and non-abstract methods. | An interface can have only abstract methods. |
4 | In abstract class keyword “abstract” is mandatory to declare a method as an abstract | In an interface keyword “abstract” is optional to declare a method as an abstract |
5 | Abstract class doesn’t support multiple inheritance. | An Interface support multiple inheritance. |
6 | An abstract class can have protected and public abstract methods | An interface can have only have public abstract methods |
7 | An abstract class can be extended using keyword “extends”. | An interface can be implemented using keyword “implements”. |
8 | An abstract class can have static, final or static final variable with any access specifier | interface can only have public static final (constant) variable |
9 | Example: public abstract class Example{ public abstract void exam(); } | Example: public interface Example{ void exam(); } |
Simply, interface achieves full abstraction (100%) whereas abstract class achieves partial abstraction (0 to 100%) .
Java Interface Example
interface Vechile {
public void test();
}
class Bike implements Vechile {
public void test() {
System.out.println("Interface Method Implemented");
}
public static void main(String args[]) {
Vechile p = new Bike();
p.test();
}
}
Abstract class example
abstract class Shape {
int b = 20;
abstract public void calculateArea();
}
public class Square extends Shape {
public static void main(String args[]) {
Square obj = new Square();
obj.b = 200;
obj.calculateArea();
}
public void calculateArea() {
System.out.println("Area is " + (obj.b * obj.b));
}
}