Tags

, ,

Inheritance is another important concept of Object Oriented Programming.

It’s not uncommon for classes to share some properties or methods. For e.g. All cars will have 4 wheels which is a common property. All cars will have methods like start, stop and accelerate, which are the common methods. This is when inheritance is used. The common properties and methods are defined for the parent class. The child class, using inheritance, will inherit these from the parent class.

Additionally, the child classes can have their own properties and methods, which make them unique.

— Child class is also referred to as derived class/ extended class.
— Parent Class is also called base class or super class.
— By default, the superclass is Object class (when there is no explicit super class)in other words, Object class is always at the top of any class hierarchy.
— Inheritance means an “IS-A” relatioship. For e.g. “Car is a vehicle”.
— Java allows only one level of inheritance, i.e. each class can inherit from only one superclass. However, one parent class can have multiple child classes.
— You can have the same property as parent class declared in a child class, this is hiding the parent’s property.
— Constructors are not inherited by a subclass.
— Private members of the super class are not inherited by the subclass.
— Inheritance allows code-reuse.

Following simple code shows how Car class inherits the vehicle class.


public class vehicle {

	int wheels = 4;
	String model;
	
	
	public static void start() {
		System.out.println(" Start");
		
	}
	
	public static void stop(){
		System.out.println("Stop");
	}
	
}
	class Car extends vehicle {  // Inheritance
		String transmission; // exclusive property for Car class.
		
		public  void Carmethod(){
			System.out.println("This method is for Car class only ");
		}
		
	
	
	public static void main(String[] args) {
		
		Car myCar1 = new Car();  // First Car Object
		myCar1.model = "BMW";
		
		myCar1.transmission = "Manual";
		
		Car myCar2 = new Car();  // Second Car Object
		myCar2.model = "Toyota";
		
		myCar2.transmission = "Automatic";

		System.out.println(myCar1.wheels);
		System.out.println(myCar1.model);
		System.out.println(myCar1.transmission);
		myCar1.Carmethod();
		
		System.out.println(myCar2.wheels);
		System.out.println(myCar2.model);
		System.out.println(myCar2.transmission);
		myCar2.Carmethod();
	}
	
	}

Advertisements