Inheritance - Object-oriented programming (Parent-Child)

                                                                                                Facebook - Free social media icons https://www.facebook.com/techaddaa/ 


Hey Friends, 

This is third post in core java concepts blog. This series is specially designed for beginners to help them in their learning.

Introduction - 

There are many concepts like Classes, Object,  Polymorphism, Inheritance etc. As concluded in second post, here we will explore important concept called "inheritance" and learn types of inheritance, it's advantages along with implementation in java language.

This concept is simple to understand. Like in real world, every child get few habits from their parent inherently similarly in programming child classes inherit behaviour from parent class.

Parent class is also called super class, base class and child class is also called sub class, derived class.

This relationship is called as parent-child relationship or IS-A relationship. For example animal class in below diagram. Dog IS-A animal similarly Cat IS-A animal too. This is general guideline while implementing this, whenever you find such relationship between objects then we should use inheritance.


                        Object Oriented Programming in C++ - GeeksforGeeks



Prerequisite - 

What is Inheritance?

Definitions@Oracle website -  A class that is derived from another class is called a subclass (also a derived classextended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class)

The idea of inheritance is simple but powerful. When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. While doing this, you can reuse the fields and methods of the existing class without having to write (and debug) them yourself.

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

                            Object Oriented Programming in Java | Java OOPs Concepts | Edureka



Types of inheritance - 


Single InheritanceIn single inheritance, subclasses inherit the features of one superclass. In image below, the class A serves as a base class for the derived class B.

Multilevel InheritanceIn Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. In below image, the class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s members.

Hierarchical InheritanceIn Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub class.In below image, the class A serves as a base class for the derived class B,C and D.

Hybrid Inheritance(Through Interfaces) It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces.

 
     Java Inheritance

To keep it simple, we will implement Single inheritance now & for other types of inheritance, we will surely look into new posts.  

Implementation -

We will continue with our Calc class example, created in previous post.

package com.utility;

public class Calc {

public void add(int a, int b) { // this method will add two numbers
System.out.println("a+b = " + a+b );
}

public void add(int a, int b, int c) { // this method will add three numbers
System.out.println("a+b+c = " + a+b+c );
}
public void add(String a, String b) { // this method will add two strings
System.out.println("a +b = " + a.concat(b) );
}
}

Lets assume we want a calculator which can perform subtraction(-) too along with addition(+). We can deliver this requirement in two ways. 

1. Create a class which will have add method same as above and define another method subtract in new class. In this way we have to write both the methods and test too.
2. Use inheritance. define new class extend from class Calc and add new subtract method. add method will automatically available because of inheritance. 
So you can see which is better way and gives us better code re usability. In second approach we are writing less code and ultimate reduce of our testing time too.

As most of us are agreed to point 2. Lets see how we can implement inheritance in java.

package com.utility;

public class AdvanceCalc extends Calc{
public void subtract(int a, int b) { // this method will subtract second number from first number
System.out.println("a-b = " + (a-b) );
}
}

extends keyword is provided by java to implement inheritance.

We will see in demo class, how inheritance helps us to reduce code lines and reuse existing classes and code.

package com.demo;

import com.utility.AdvanceCalc;

public class InheritanceDemo {

public static void main(String[] args) {

AdvanceCalc calc = new AdvanceCalc();

calc.add(5,6);
calc.subtract(50,10);
calc.add("Single"," Inheritance");

}

}

 

AdvanceCalc does not have definition of add method but still that method available to use. Subclass AdvanceCalc is extend Super class Calc class so it is inherit all the method and make available to use.

Output of above demo class.
a+b = 56
a-b = 40
a +b = Single Inheritance

Process finished with exit code 0


Bonus Points - 

  • Default superclass: Except Object class, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object class.
  • Superclass can only be one: A superclass can have any number of subclasses. But a subclass can have only one superclass. This is because Java does not support multiple inheritance with classes. Although with interfaces, multiple inheritance is supported by java.
  • Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
  • Private member inheritance: A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods(like getters and setters) for accessing its private fields, these can also be used by the subclass.
      Do's and Don't in a Subclass?

      In sub-classes we can inherit members as is, replace them, hide them or supplement them with new members:

  • The inherited fields can be used directly, just like any other fields.
  • We can declare new fields in the subclass that are not in the superclass.
  • The inherited methods can be used directly as they are.
  • We can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it (as in example above, toString() method is overridden).
  • We can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
  • We can declare new methods in the subclass that are not in the superclass.
  • We can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.
  • Don't get confuse between interface and inheritance.

Till here, we have learned -

1. Create class
2. Create Object
3. Define methods 
4. Overload methods
5. Method Calling
6. Single Inheritance

Upcoming Posts - 

We will have more fun and learning in upcoming weeks. Bookmark this space in your favourites.  

1. Runtime Polymorphism - Part 2
2. Type of Inheritance - Part 2
3. Constructors in class 

You can also suggest your favourite topics in comments section or on Facebook page. We will try to start exploring on those topic. You can also suggest points to make blogs more effective.

To connect more and discuss technology, Please visit and like the page. We will list all the posts there and provide updates about upcoming events/posts.

https://www.facebook.com/techaddaa/


Happy Learning and keep Sharing !!!!

Comments

Popular posts from this blog

Polymorphism Part 1 (Compile Time Polymorphism)

Class & Object in java - Do you know ?????