Skip to main content

Inheritance in Java with example

Inheritance is a concept in java where new classes can be produced from existing classes. The newly created class acquires all the features of existing class from where it is derived.
         
          Inheritance can be implemented in java using two keywords:
          1.  extends              2. implements

          Producing new class from existing classes is called inheritance.
             •     The newly produced class is called sub class. The original class is called super class.
             •     Extends is the keyword use in inheritance.

Syntax:

1
class SubClass extends SuperClass

             •   Reusability is the main advantage of inheritance
             •   Because of reusability developing of software/program becomes easy.
             •  Sub class contains a copy of super class
             •  In inheritance, we create object to only sub class. Because in sub class it contains all the methods & objects of a class are available to sub class.

Case 1: If super class has default constructor

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.javatbrains.oops;

class One{
     One(){
          System.out.println("Inside One class");
     }
}

class Two extends One{
     Two(){
          System.out.println("Inside Two class");
     }
}

public class ConstDemo {

     public static void main(String[] args) {
          new Two();
     }

}
OutPut:
     Inside One class
     Inside Two class

              •  When you create an object to sub class to super class constructor is also available to sub class.
              •   Super class default constructor also available to sub class.
              •   Super class parametrised constructor is not available in subclass.

Case 2: If super class has parametrised constructor

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.javatbrains.oops;

class One1 {
     int i;

     One1(int i) {
          this.i = i;
     }

     void show() {
          System.out.println("Super class method = " + i);
     }
}

class Two2 extends One1 {
     int i;

     Two2(int x, int y) {
          super(x);  //Calling Super class default constructor
          i = y;
     }

     void show() {
          System.out.println("Sub class method = " + i);
          System.out.println(super.i);
          super.show(); //Calling Super class show method
     }

}

public class ParamConstDemo {

     public static void main(String[] args) {
          Two2 t = new Two2(100, 200);
          t.show();
     }

}
OutPut:
     Sub class method = 200
     100
     Super class method = 100

               •  Super keyword refers to super class from sub class
               •   Using super keyword we can refer to super class instance variables constructors, methods also.
               •  Super.show() in sub class. It shows super class method.
               •  We have to initialize first super class constructor.

Types of Inheritance:
Single Inheritance: Producing sub classes from super class is called single inheritance.

Multiple Inheritance: Producing sub classes from multiple super classes is called multiple inheritance.

               •  Multiple inheritance does not support in java.

Why multiple inheritance is not available in Java?
          Multiple inheritance leads to confusion for programmer. This is against to the aim of java be a simple programming language.
          Java = C++ -Complexity
          There is no operator loading in java. There is no destructor in java. Destructor work is done by Garbage collector.

How can you call garbage collector?
          By calling System.gc(); It will runs the garbage collector. Runtime and system classes of java.lang package System.gc() is available.

Can you create object for System class?
          No, it is not possible. System class can not be instantiated because it contains static methods. finalize() method belongs to class of java.lang package. finalize() method destroys the memory. If you call the finalize() it may crash the program, so it is better to avoid calling finalize() method.
         
          finalize() method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because java has only finite number of these resources and you do not know when the garbage collection is going to Kick in to release these non-memory resources through the finalize() method.

          Garbage collector will work automatically; we should not required to call it.

        1. Multiple inheritance can be achieved by programmers by using interfaces.

1
2
3
class Z extends A,B (Invalid)

class Z implements A,B (Valid)

          A class can implement more than one interface.

        2. Multiple inheritance can be achieved by repeated use of single inheritance.
Hybrid inheritance in the above image first line represents the multiple inheritance and last line represents the single inheritance. So, this is the combination of multiple and single inheritance.

Ex: Multiple inheritance example with interface

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.javatbrains.oops;

interface Father{
     //variables are by default public static final
     int prop1 = 500000;
     float ht1 = 6.0f;
}

interface Mother{
     int prop2 = 900000;
     float ht2 = 5.6f;
}

class Child implements Father,Mother{
    
     void property(){
          System.out.println("Child property is = "+(prop1+prop2));
     }
     void height(){
          System.out.println("Child height is = "+(ht1+ht2)/2);
     }
}

public class Multi {

     public static void main(String[] args) {
          Child ch = new Child();
          ch.property();
          ch.height();
     }
}

OutPut:
     Child property is = 1400000
     Child height is = 5.8

Encapsulation, IS-A, HAS-A:
           •   Encapsulation helps hide implementation behind an interface.
           •   Encapsulated code has two features
           •   Instance variables are kept protected(usually with the private modifier)
           •   Getter and Setter methods provide access to instance variables.
           •    IS-A refers to inheritance or implementation
           •    IS-A is expressed with the keyword extends
           •    IS-A, "inherits from" and "is a subtype of" are all equivalent expressions.
           •    HAS-A means an instance of one class "has a" reference to an instance of another class or another instance of the same class.

Inheritance:
           •   Inheritance allows a class to be a subclass of a super class, and thereby inherit public class protected variables and methods of the super class.
           •  Inheritance is a key concept that underlies IS-A, polymorphism, overriding, overloading and casting.
           •   All classes (except class Object), are subclasses of type Object, and therefore they inherit Objects methods.

Comments

Popular posts from this blog

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...