Please disable adblock to view this page.

← Go home

Abstract in Java


May 2, 2017
Published By : Pratik Kataria
Categorised in:

Understanding through Code (abstract class)


public abstract class Bike {

	public static final String HONDA = "Honda";
	public static final String YAMAHA = "Yamaha";

	private String name = HONDA;
	private String color = "Red";
	private int gearOrNot = 1;

	public Bike(String name, String color, int gearOrNot) { = name; 
		this.color = color;
		this.gearOrNot = gearOrNot;

	public String getName() { return name; }

	public String getColor() { return color; }

	public int getGearOrNot() { return gearOrNot; }

	public abstract String getLogo();



import java.util.List;

public interface Details {
	public void getDetails(List<Bike> bikes);

	public void setColor(String color);



//FOr demonstrating instance method
import java.util.List;

public class VehicleTypes implements Details {

	private String colorChoice;

	public void getDetails(List<Bike> bikes) { 
		String colorChoiceOfCustomer = colorChoice;

		for(Bike b: bikes) {
		 	System.out.println(b.getName() +" " + b.getColor() + " " + b.getGearOrNot());

		System.out.println("Color choice is: " +colorChoiceOfCustomer);


	public void setColor(String color) {
		colorChoice = color;



public class Honda extends Bike {

	public Honda() {
		super(Bike.HONDA, "Red", 1);

	public String getLogo() {
		return "Find logo on google please...";



import java.util.List;
import java.util.ArrayList;

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

		List<Bike> bikes = new ArrayList<>();

		bikes.add(new Honda());

		//Below line will produce error that bike is abstract and cannot be instantiated
		//bikes.add(new Bike(Bike.YAMAHA, "Black", 1)); 

		Details vt = new VehicleTypes();
		System.out.println( (new Honda()).getLogo() );



  • K:\Abstract>javac com\example\java\model\
  • K:\Abstract>javac com\example\java\
  • K:\Abstract>javac com\example\java\
  • K:\Abstract>javac com\example\java\
  • K:\Abstract>java
  • Honda Red 1
  • Color choice is: White
  • Find logo on google please…


  • An abstract class is determined by the abstract keyword. It can contain combination of:
    • Fully implemented methods
    • Abstract methods
  • An abstract method is just like a method in an interface i.e. it does not have any implementation.
  • Any subclasses of an abstract class must implement that abstract method.
  • In above code, Bike is superclass for Honda. That is, Honda is subclass of Bike.
  • When we declared an abstract method after making the Bike class abstract:
    • public abstract String getLogo();
  • We get an error to either: (1) declare honda as abstract or (2) implement the abstract method.
  • Abstract classes cannot be instantiated directly. Only their subclasses can be instantiated.
  • Abstract is similar to interface. A programmer determines whether to use interface or abstract depending on application’s needs.