What is the difference between abstract class and a concrete class in Java?
Following are the notable differences between an abstract class and concrete class.
Abstract class
- Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); )
- But, if a class has at least one abstract method, then the class must be declared abstract.
- You cannot instantiate an abstract class.
- An abstract class may contain abstract methods.
- You need to inherit an abstract class to use it.
- If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.
Example
public abstract class AbstractExample {
public abstract int add(int a, int b);
public abstract int subtract();
public void display(){
System.out.println("Hello how are you");
}
}
Concreate class
- You can instantiate a concrete class.
- A concrete class doesn’t have any abstract methods.
- It is not mandatory to inherit a concrete class to use it.
Example
Live Demo
public class ConcreteClassExample {
public int add(int a, int b){
int c = a + b;
return c;
}
public int subtract(int a, int b){
int c = a - b;
return c;
}
public void display(){
System.out.println("Hi welcome to Tutorialspoint");
}
public static void main(String args[]){
ConcreteClassExample obj = new ConcreteClassExample();
System.out.println(obj.add(25, 347));
System.out.println(obj.subtract(500, 456));
obj.display();
}
}
Output
372
44
Hi welcome to Tutorialspoint
Published on 29-Dec-2017 09:31:35