Inheritance in Java

inheritance

Inheritance in Java

Inheritance is a mechanism that allows us to extend the definition of a class without making any physical changes to the existing class.

Inheritance creates a new class from an existing class. Any new class that we create from an existing class is called a derived class, and an existing class is called a base class.

Concept and Types of inheritance

The inheritance relationship enables a derived class to inherit features from its base class. A derived class can add new features of its own. Therefore rather than creating completely new classes from scratch, we can take advantage of inheritance and reduce software complexity.

  • Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
  • Sub Class/Child Class: Subclass is a class that inherits the other class. It is also called a derived class, extended class, or child class.
  • Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
  • Reusability: As the name specifies, reusability is a mechanism that facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.

Types of inheritance :

  • Single Inheritance
  • Multiple Inheritance
  • Hierarchical Inheritance
  • Multilevel Inheritance
  • Hybrid Inheritance
java inheritance

1. Single Inheritance 

It is the inheritance hierarchy wherein one derived class inherits from one base class.

 

2. Multiple Inheritance 

It is the inheritance hierarchy wherein one derived class inherits from multiple base classes.

 

3. Hierarchical  Inheritance 

It is the inheritance hierarchy wherein multiple derived classes inherit from one base class.

 

4. Multilevel  Inheritance 

It is the inheritance hierarchy wherein subclass acts as a base class for other classes.

5. Hybrid  Inheritance 

It is the inheritance hierarchy that reflects any legal combination of the other four types of inheritance

Syntax

class XYZ extends ABC
  {   
       // block of code
  }

Example

Run
class Bicycle 
{ 
	// the Bicycle class has two fields 
	public int gear; 
	public int speed; 
		
	// the Bicycle class has one constructor 
	public Bicycle(int gear, int speed) 
	{ 
		this.gear = gear; 
		this.speed = speed; 
	} 
		
	// the Bicycle class has three methods 
	public void applyBrake(int decrement) 
	{ 
		speed -= decrement; 
	} 
		
	public void speedUp(int increment) 
	{ 
		speed += increment; 
	} 
	
	// toString() method to print info of Bicycle 
	public String toString() 
	{ 
		return("No of gears are "+gear 
				+"\n"
				+ "speed of bicycle is "+speed); 
	} 
} 

// derived class 
class MountainBike extends Bicycle 
{ 
	
	// the MountainBike subclass adds one more field 
	public int seatHeight; 

	// the MountainBike subclass has one constructor 
	public MountainBike(int gear,int speed, 
						int startHeight) 
	{ 
		// invoking base-class(Bicycle) constructor 
		super(gear, speed); 
		seatHeight = startHeight; 
	} 
		
	// the MountainBike subclass adds one more method 
	public void setHeight(int newValue) 
	{ 
		seatHeight = newValue; 
	} 
	
	// overriding toString() method 
	// of Bicycle to print more info 
	@Override
	public String toString() 
	{ 
		return (super.toString()+ 
				"\nseat height is "+seatHeight); 
	} 
	
} 

// driver class 
public class Test 
{ 
	public static void main(String args[]) 
	{ 
		
		MountainBike mb = new MountainBike(3, 100, 25); 
		System.out.println(mb.toString()); 
			
	} 
}

Output

No. of gears are 3

The speed of bicycle is 100

Seat height is 25
 

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

Inheritance in Python

Inheritance in Python:

Inheritance in Python is the capability of one class to derive or inherit the properties from another class. In inheritance, the child class acquires the properties and can access all the data members and functions defined in the parent class. A child class can also provide its specific implementation to the functions of the parent class.  

Example: 

  • Class A:

             //pass 

         Class B(A):

           //pass

Inheritance in Python

Benefits of Inheritance: 

  • Reusability of code.
  • We can use the features of the other class, without modifying it.
  • It is transitive in nature i.e. A->B->C == A->C and B->C.  

Syntax: 

class Parentclass_name: 

 ##statement  

class child_class(Parentclass_name): 

  ##statement

Different forms of Inheritance:

  •  Single inheritance: When a child class inherits from only one parent class, it is called single inheritance. 

 

 

Code #1:

#python Program
#Rishikesh 
#singel level inheritence
# Creating a PrepInsta class
class PrepInsta:
    def __init__(self,a):
        self.a =a
        print(self.a)

# Creating a Prepster class 
class Prepster(PrepInsta):
    def __init__(self,a):
        
        # Calling constructor of
        # PrepInsta class
        PrepInsta.__init__(self,a) 
        

obj1 = Prepster(5
  • Multiple inheritance: When a child class inherits from multiple parent classes, it is called multiple inheritance

Code #2:

#python Program
#Rishikesh 
#multiple inheritence
 
class A(object): 
    def __init__(self): 
        self.str1 = “PrepInsta”
        print(“A”

class B(object): 
    def __init__(self): 
        self.str2 = “Prepster”      
        print(“B”

class C(AB): 
    def __init__(self): 
        
        # Calling constructors of A 
        # and B classes 
        A.__init__(self
        B.__init__(self
        print(“C”
        
    def printStrs(self): 
        print(self.str1, self.str2) 
        

ob = C() 
ob.printStrs() 

Output: 

A
B
C
PrepInsta Prepster
types inheritance in Python
  •  Multilevel inheritance: When we have a child and grandchild type relationship. 

Code #3

#python Program
#Rishikesh 
#multilevel inheritence
 
class A(object): 
    def __init__(self): 
        self.str1 = “PrepInsta”
        print(“A”

class B(A): 
    def __init__(self): 
        self.str2 = “Prepster”   
        A.__init__(self
        print(“B”

class C(B): 
    def __init__(self): 
        
        # Calling constructors of A 
        # and B classes 
        B.__init__(self
        print(“C”
        
    def printStrs(self): 
        print(self.str1, self.str2) 
        

ob = C() 
ob.printStrs() 

Output: 

A
B
C
PrepInsta Prepster
  • Hierarchical inheritance More than one derived classes are created from a single parent.
  •  Hybrid inheritance: This form combines more than one form of inheritance. Basically, it is a mixture of more than one type of inheritance.