How to Java programming- Inheritance

Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes.

Java inheritance

The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class, and you can add new methods and fields also.

Let’s consider a superclass Vehicle. Different vehicles have different features and properties however there few of them are common to all. Speed, color, fuel used are few which are common to all. Hence we can create a class ‘Vehicle’ with states and actions that are common to all vehicles. The subclass of this superclass can be any type of vehicle. Example: Class Car A has all the features of a vehicle. But it has its own attributes which make it different from other subclasses. By using inheritance we need not rewrite the code that we’ve already used with the Vehicle. The subclass can also be extended. We can make a class ‘Sports Car’ which extends ‘Car’. It inherits the features of both ‘Vehicle’ and ‘Car’.

Java Inheritance
	// A class to display the attributes of the vehicle
	class Vehicle {
	   String color;
	   int speed;
	   int size;
	   void attributes() {
		  System.out.println("Color : " + color);
		  System.out.println("Speed : " + speed);
		  System.out.println("Size : " + size);
	   }
	}

	// A subclass which extends for vehicle
	class Car extends Vehicle {
	   int CC;
	   int gears;
	   void attributescar() {
		  // The subclass refers to the members of the superclass
		  System.out.println("Color of Car : " + color);
		  System.out.println("Speed of Car : " + speed);
		  System.out.println("Size of Car : " + size);
		  System.out.println("CC of Car : " + CC);
		  System.out.println("No of gears of Car : " + gears);
	   }
	}
	public class Test {
	   public static void main(String args[]) {
		  Car b1 = new Car();
		  b1.color = "Blue";
		  b1.speed = 200 ;
		  b1.size = 22;
		  b1.CC = 1000;
		  b1.gears = 5;
		  b1.attributescar();
	   }
	}

 

Output
	Color of Car : Blue
	Speed of Car : 200
	Size of Car : 22
	CC of Car : 1000
	No of gears of Car : 5

 

Inheritance in Java used for Method Overriding and for Code Reusability.

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...