OOP Concept: What is Inheritance in java?

What is Inheritance in java?

Inheritance is an important part of Object-Oriented Programming (OOP) languages.

Inheritance is a mechanism where one class acquires all the properties and behaviors (methods and fields) of another class is called Inheritance.

We use extends Keyword to inherit the properties of one class to another class.

Using the extends keyword, the child class will be able to inherit all the properties of the parent class but
except for the private properties of the parent class.

 

The syntax of Java Inheritance Example:

class Parent {
.....
.....
}

class Child extends Parent {
.....
.....
}


 

In the above example Parent class is called superclass and childclass is called subclass, where child class extends the Parent class and gets all properties and behaviors of the parent class.

If any class extends to any other class using the keyword extends mean’s that class is child class.

Every class has superClass except one class that is Object class. Object class the only class in Java that doesn’t extend another class.

If you don’t declare a superclass of your class than your class implicitly extends the class Object as a supperClass.

 

Why use inheritance in java?

  • For Method Overriding.
  • For Code Re-usability.

 

What is the benefit of using inheritance in java?

Using Method Overriding we can be achieved runtime polymorphism in java. Code Reusability,  reusability is a mechanism which provides facilitates you to reuse the fields and methods of the existing class (Parent Class)
when you create a new class (Child class). You can use the same fields and methods already defined in the Parent class.

 

IS-A Relationship Example.

public class Animal {
}

public class Dog extends Animal {
}

public class Cat extends Animal {
}


In the above example Dog is the subclass and Animal is the superclass. The relationship between the two classes is Dog IS-A Animal and Cat IS-A Animal. It means that Dog is a type of Animal and also Cat is a type of Animal.

 

Java Inheritance program Example:

package com.testing;

//concept of inheritance 

//base class 
class Father  
{ 
 // the Father class has two fields 
 public int money; 
 public int gold; 
       
 // the Father class has one constructor 
 public Father(int money, int gold) 
 { 
     this.money = money; 
     this.gold = gold; 
 } 
       
 // the Father class has three methods 
 public void subtractMoney(int decrement) 
 { 
	 money -= decrement; 
 } 
       
 public void addMoney(int increment) 
 { 
	 money += increment; 
 } 
   
 // toString() method to print info of Father 
 public String toString()  
 { 
     return("Kg of gold are "+gold 
             +"\n"
             + "Money of Father is "+money); 
 }  
} 

//derived class 
class Son extends Father  
{ 
   
 // the Son subclass adds one more field 
 public int house; 

 // the Son subclass has one constructor 
 public Son(int gold,int money, 
                     int noOfHouse) 
 { 
     // invoking base-class(Father) constructor 
     super(gold, money); 
     house = noOfHouse; 
 }  
       
 // the Son subclass adds one more method 
 public void setHouse(int newValue) 
 { 
	 house = newValue; 
 }  
   
 // overriding toString() method 
 // of Father to print more info 
 @Override
 public String toString() 
 { 
     return (super.toString()+ 
             "\nNumber of house is "+house); 
 } 
   
} 

//driver class 
public class Test  
{ 
 public static void main(String args[])  
 { 
       
     Son son = new Son(100000,3, 2); 
     System.out.println(son.toString()); 
           
 } 
}

Output:

Kg of gold are 3
Money of Father is 100000
Number of house is 2

 

In the above program, when we created the object of Son class, a copy of the all methods and fields of the superclass (Father class) acquire memory in the object of son class. That is why by using the object of the child class we can also access the members of a parent class.

 

Types of Inheritance in Java

There are different types of inheritance.
Below are the different types of inheritance which are supported by Java.

  • Single Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Multiple Inheritance
  • Hybrid Inheritance

 

What is Single Inheritance?

When subclasses inherit the features of one superclass is known as single inheritance.

In the above image, A class is a base class for the derived class B.

 

Single Inheritance Example:

package com.testing;
class Animal {
	void eat() {
		System.out.println("Animal are eating....");
	}
}

class Cat extends Animal {
	void meow() {
		System.out.println("Cat is meow");
	}
}

class Test{
	public static void main(String args[]) {
		Cat cat = new Cat();
		cat.meow();
		cat.eat();
	}
}

OutPut:

Cat is meow.... Animal are eating....

In the above example, the Cat class inherits the features of the Animal class.

 

What is Multilevel Inheritance?

When one class inherits multiple class features, is known as a multilevel inheritance in java.

In Java, any driving class can not directly access the grandparent’s members. like C class can not directly inherit the features of A-class. C class inherits the features of A-class through B class.

In the above image, C class inherits the features of B class, and it also inherits the features of A-class through B class.

 

Multilevel Inheritance Example:

package com.testing;
class Animal {
	void eat() {
		System.out.println("Animal are eating....");
	}
}

class Cat extends Animal {
	void meow() {
		System.out.println("Cat is meow");
	}
}

class Test{
	public static void main(String args[]) {
		Cat cat = new Cat();
		cat.meow();
		cat.eat();
	}
}

OutPut:

Cat is meow....
Animal are eating....

In the above example, the Cat class inherits the features of the Animal class.

 

What is Multilevel Inheritance?

When one class inherits multiple class features, is known as a multilevel inheritance in java. In Java, any driving class can not directly access the grandparent’s members. like C class can not directly inherit the features of A-class. C class inherits the features of A-class through B class.

In the above image, C class inherits the features of B class, and it also inherits the features of A-class through B class.

 

Multilevel Inheritance Example:

package com.testing;

class Animal {
	void eat() {
		System.out.println("Animal are eating....");
	}
}

class Cat extends Animal {
	void meow() {
		System.out.println("Cat is meow....");
	}
}

class Kitten extends Cat {
	void weep() {
		System.out.println("Kitten is weeping....");
	}
}

class Test {
	public static void main(String args[]) {
		Kitten k = new Kitten();
		k.weep();
		k.meow();
		k.eat();
	}
}

OutPut:

Kitten is weeping....
Cat is meow....
Animal are eating....

 

In the example given above, the Kitten class inherits the Cat class which again inherits the Animal class, so there is a multilevel inheritance.
As you can see in the example Kitten class can not directly inherit the features of Animal class, It can inherit the features of Animal class through Cat class.

 

What is Hierarchical Inheritance in java?

When a single class is inherited by multiple classes, it is known as hierarchical inheritance

In the above image, A class is inherited by class B and C.

 

Hierarchical Inheritance Example:

package com.testing;
class Animal {
	void eat() {
		System.out.println("Animal are eating....");
	}
}

class Cat extends Animal {
	void meow() {
		System.out.println("Cat is meow....");
	}
}

class Dog extends Animal {
	void bark() {
		System.out.println("Dog is barking....");
	}
}

class Test {
	public static void main(String args[]) {
		Cat c = new Cat();
		c.meow();
		c.eat();
		Dog d = new Dog();
		d.bark();
		d.eat();
	}
}

Output:

Cat is meow....
Animal are eating....
Dog is barking....
Animal are eating....

In the example given above, the Cat class inherits the Animal class, and the Dog class also inherits the Animal class so there is a Hierarchical inheritance.

 

What is Multiple Inheritance?

When one subClass has multiple superclass and inherits features from all parent classes, is known as Multiple inheritances in java.

In Java, multiple Inheritance is not supported by Java Class, but we can achieve multiple Inheritance through Interfaces in Java

In the above image, C class is inherited by class A and B

 

What is Hybrid Inheritance?

Hybrid Inheritance is a mix of two or more different types of inheritance.

We already know Java does not support multiple inheritances through classes, so Hybrid Inheritance is also not supported by multiple inheritances through classes. It can also achieve through Interfaces in Java.

 

Why Multiple Inheritance is not supported by Java Class?

Multiple Inheritance is not supported by Java class because of the ambiguity problem.

Let’s try to understand through example, suppose A, B, and C are three classes. C class inherits A and B classes.
Now if A and B classes have the same method with all functionality and you call it from C class(child class) object, there will be ambiguity to call the method of A or B class. The C class object not able to identify to which class object need to call because in both class method is same.

 

Multiple Inheritance Example:

package com.testing;

class A {
	void msg() {
	System.out.println("How are you?");
	}
}

class B {
	void msg() {
	System.out.println("You are from?");
	}
}

class C extends A,B{ 
     public static void main(String args[]) {
      C obj = new C();
      obj.msg();
    }
}

Output:

Compile Time Error

Hope this was helpful for you. If you have any questions please feel free to leave a comment. Thank you for reading.

17 Replies to “OOP Concept: What is Inheritance in java?”

  1. I am just writing to make you understand what a notable experience my wife’s girl had using your web site. She mastered so many pieces, which included what it is like to possess an excellent helping nature to let other people with ease learn some problematic things. You truly surpassed people’s expected results. Thank you for producing these precious, trusted, informative and in addition fun tips about this topic to Lizeth.

  2. I needed to draft you one little bit of observation so as to say thank you once again for those incredible methods you’ve documented here. It is quite pretty generous of people like you to deliver freely exactly what a number of people could possibly have made available as an e book to end up making some cash for themselves, even more so given that you could possibly have done it if you ever decided. These inspiring ideas also served like the fantastic way to comprehend other individuals have similar eagerness like my own to know great deal more on the subject of this issue. I’m sure there are many more fun occasions in the future for individuals who look into your blog post.

  3. My husband and i ended up being comfortable Albert could carry out his basic research because of the ideas he acquired from your blog. It’s not at all simplistic just to always be freely giving guidance many others could have been making money from. And now we already know we’ve got the blog owner to appreciate because of that. All of the explanations you’ve made, the easy blog menu, the friendships you aid to create – it’s all astonishing, and it’s aiding our son and our family believe that that article is awesome, and that’s exceedingly essential. Many thanks for all!

  4. I simply wished to thank you very much yet again. I do not know what I would have used without those tips and hints shown by you relating to this theme. This has been the traumatic setting in my view, nevertheless viewing your well-written technique you treated the issue took me to weep with joy. Now i am thankful for your work as well as wish you recognize what an amazing job your are undertaking training the others with the aid of your website. Probably you haven’t met any of us.

  5. I precisely needed to appreciate you once again. I am not sure the things that I might have gone through in the absence of the entire pointers provided by you on such a problem. It had been a very frightening difficulty in my circumstances, however , looking at the skilled manner you processed that made me to jump over fulfillment. I am happier for this help and in addition hope you know what a great job you are getting into instructing others through the use of your site. I know that you have never encountered all of us.

  6. I’m just commenting to let you be aware of of the fabulous discovery my cousin’s daughter experienced going through your site. She even learned lots of issues, most notably how it is like to have a very effective giving mindset to have many others just gain knowledge of chosen grueling matters. You really did more than our desires. Many thanks for distributing the important, healthy, educational and as well as easy thoughts on the topic to Gloria.

  7. A lot of thanks for all your valuable hard work on this web page. Kate loves getting into investigation and it’s really easy to understand why. I know all of the dynamic medium you make insightful solutions on this web blog and as well as foster participation from people on that idea so our girl is certainly discovering a lot of things. Have fun with the remaining portion of the new year. You are conducting a powerful job.

  8. My spouse and i got quite happy that John could deal with his preliminary research through the ideas he grabbed out of your web page. It’s not at all simplistic to just continually be giving out points that many others have been selling. And we also fully understand we have got the website owner to be grateful to for that. The main explanations you have made, the simple site menu, the friendships you can help foster – it’s got many impressive, and it’s really helping our son and the family imagine that the matter is excellent, and that is pretty indispensable. Thank you for everything!

  9. Thank you for your entire labor on this web site. My mom really loves managing investigations and it is obvious why. My partner and i learn all regarding the lively tactic you present sensible things through your web site and in addition invigorate response from some others on the situation then our favorite princess is really starting to learn a whole lot. Take advantage of the rest of the year. You have been doing a stunning job.

  10. I happen to be writing to make you understand what a terrific experience our princess went through visiting yuor web blog. She realized too many things, with the inclusion of what it is like to possess an incredible teaching style to make the others without hassle thoroughly grasp various tricky topics. You undoubtedly surpassed visitors’ expected results. Thanks for showing those warm and friendly, trustworthy, revealing not to mention unique tips on your topic to Tanya.

  11. My spouse and i have been really joyous that Jordan managed to do his reports through your precious recommendations he had through the web pages. It is now and again perplexing to just find yourself handing out secrets and techniques which people today may have been selling. So we keep in mind we need the writer to give thanks to for that. The most important illustrations you have made, the simple web site navigation, the relationships you will help to instill – it’s got most overwhelming, and it’s really leading our son in addition to the family reason why the situation is exciting, which is rather mandatory. Thank you for the whole lot!

  12. Woah! I’m really enjoying the template/theme of this blog.
    It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance” between usability and appearance.
    I must say you’ve done a awesome job with this.
    Also, the blog loads super fast for me on Opera. Excellent Blog!

Leave a Reply

Your email address will not be published.