Please disable adblock to view this page.

← Go home

Extending Classes and Super in Java


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

Let’s Dive into the Code file in folder path: K:\Extending Classes and Overriding Methods\com\example\java


import*;	//This imports all the files in model folder
import java.util.List;
import java.util.ArrayList;

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

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

		//Instead of:
		//bikes.add(new Bike(Bike.HONDA, 0x2E0456, 1));
		//We do this as Honda knows all the values:
		bikes.add(new Honda());
		bikes.add(new Bike(Bike.YAMAHA, 0x2E0854, 1));
		bikes.add(new Bike(Bike.YAMAHA, 0x2E0555, 1));

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

} file in folder path: K:\Extending Classes and Overriding Methods\com\example\java\model


public class Bike {

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

	private String name = HONDA; 
	private long color = 0x2E0456;
	private int gearOrNot = 1;

	//Let's forget to create the default constructor
	//public Bike() {} //does nothing but must be defined and public

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

	public String getName() { return name; }

	public long getColor() { return color; }

	public int getGearOrNot() { return gearOrNot; }

} file in folder path: K:\Extending Classes and Overriding Methods\com\example\java\model


public class Honda extends Bike { //will give error. Need to define default constructor
	//public Honda() {} //will give error that still no default constructor exists

	public Honda() {
		super(Bike.HONDA, 0x2E0456, 1);



  • javac com\example\java\model\
  • javac com\example\java\
  • java
  • Honda 3015766 1
  • Yamaha 3016788 1
  • Yamaha 3016021 1


  • Instead of explicitly setting name, color and gearOrNot variable, we created a special subclass Honda.
  • This subclass Honda already knows the values of name, color and gearOrNot.
  • The subclass (Honda) expects a no argument constructor in superclass (Bike).
  • Since, the no argument constructor does not exists, we need to create it explicitly in the subclass.
  • If we just define an empty default constructor in subclass, we get error again.
  • So we need to use the keyword ‘super’ to call a specific constructor from superclass.
  • super() needs to be first keyword in the definition.
  • This makes the code simpler and easier to read.
  • Now if there is a change in color then it needs to be done in subclass only and it will be reflected everywhere the subclass is instantiated.
  • Thus, subclass can contain specific information and override the default or set specific values which the superclass requires.