Site icon Narayana Tutorial

Explain with example to describe when to use abstract class and interface?

Explain with example to describe when to use abstract class and interface?

Consider a scenario where all Cars will have 4 tyres and other features can be different.

In this case any subclass of Car has to have 4 tyres. This is a case where abstract class will be used and a default implementation for tyres will be provided.

public abstract class Car { 

private final static TOTAL_TYRES=4; 

public abstract String getCarName(); 

public final int getNoOfTyres(){ 

        return TOTAL_TYRES; 

     } 
}

Consider a scenario where Cars can have any number of tyres and other features can also be different. In this case interface will be created.

public interface Car { 

public abstract String getCarName(); 

public abstract int getNoOfTyres();
 
}