Difference between Abstract Class and Interface in Java

Java Programming Java8Object Oriented Programming

Following are the notable differences between interface and abstract class in Java.

Abstract ClassInterface
An abstract class may contain concrete method.All the methods of an interface are abstract.
To use an abstract class, you need to inherit it. Provide body to (override) the abstract methods if there are any.To use an interface you need to implement the interface and provide body to (override) all the abstract methods of it.
Members of an abstract class can be public, private, protected or default.All the members of the interface are public by default.

Example

public class Tester {
   public static void main(String[] args) {

      Car car = new Car();
      car.setFuel();
      car.run();
      Truck truck = new Truck();
      truck.setFuel();
      truck.run();
   }
}
interface Vehicle {
   public void setFuel();
   public void run();
}
class Car implements Vehicle {
   public void setFuel() {
      System.out.println("Car: Tank is full.");
   }
   public void run() {
      System.out.println("Car: Running.");
   }
}
abstract class MotorVehicle {
   public void setFuel() {
      System.out.println("MotorVehicle: Tank is full.");
   }
   abstract public void run();
}
class Truck extends MotorVehicle {
   public void run() {
      System.out.println("Truck: Running.");
   }
}

Output

Car: Tank is full.
Car: Running.
MotorVehicle: Tank is full.
Truck: Running.
raja
Published on 13-Aug-2018 10:46:16
Advertisements