• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Inheritance in Java with Example Programs

August 3, 2015 by javainterviewpoint 1 Comment

Inheritance is one of the important concept in OOPs. Java Inheritance is a process by which one class can re-use the methods and fields of other class. The Derived class(Sub class – The class which inherits the Parent class) re-uses the methods and variables of the Base class(Super class).

Inheritance represents IS-A relationship which is also called as Parent-Child relationship. (i.e) A Parent class can have any number of Child class whereas a Child class can have only one Parent class. Child class inherits the Parent class using extends keyword.

Inheritance in Java Example

Lets take the below example where Cycle class is the Super class. The Cycle class will have the common properties of a cycle such as gear and speed. The sub class here is the MountainCycle which extends the Cycle class. MountainCycle will have all the attributes of a Cycle and also has its own attribute to differentiate from other sub class. Since we are using Inheritance we need not re-write the speed and gear property for the MountainCycle again.

package com.javainterviewpoint;
class Cycle {
    int gear;
    String speed;
    public Cycle(){}
    public Cycle(int gear,String speed)
    {
        this.gear = gear;
        this.speed = speed;
    }
    
 }
 // MountianCycle is the Sub Class of Cycle
 class MountianCycle extends Cycle 
 {
     String color;
     
    public MountianCycle(String color)
    {
        this.color = color;
    }
    //Method to display both Cycle and MountianCycle class attributes
    public void ride()
    {
        System.out.println("Number of Gear : \""+gear+"\"");
        System.out.println("Speed of Cycle : \""+speed+"\"");
        System.out.println("Color of Cycle : \""+color+"\"");
    }
 }
public class InheritanceTest 
{
    public static void main(String args[]) 
    {
        //Create object of the Sub Class(MountianCycle)
        MountianCycle mb = new MountianCycle("Blue");
        //Set the values to the Cycle class attributes through MountianCycle object
        mb.speed = "50kmh";
        mb.gear = 5;
        mb.ride();
     }
}

When we run the above code we will get the below output.

Output: 

Number of Gear : "5"
Speed of Cycle : "50kmh"
Color of Cycle : "Blue"

Different Types of Inheritance in Java

Below are different types of Inheritance in Java, some are directly supported and some are indirectly supported through Java Interfaces.

  1. Single Inheritance
  2. Multiple Inheritance (Through Interface)
  3. Multilevel Inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance (Through Interface)

We will be looking at each of inheritance types at later point.

Private Access Modifier in Java Inheritance

A sub class can take all the attributes of a super class which is having public and protected access, it cannot access a private members of the parent class, as the private variable belongs to that class itself. In those cases the we can access those private members of the parent class using a public access methods (getters & setters). Lets change the Cycle class to have private members.

package com.javainterviewpoint;
class Cycle {
    private int gear;
    private String speed;
    public Cycle(){}
    public Cycle(int gear,String speed)
    {
        this.gear = gear;
        this.speed = speed;
    }
    public int getGear() {
        return gear;
    }
    public void setGear(int gear) {
        this.gear = gear;
    }
    public String getSpeed() {
        return speed;
    }
    public void setSpeed(String speed) {
        this.speed = speed;
    }
}
 // MountianCycle is the Sub Class of Cycle
 class MountianCycle extends Cycle 
 {
     String color;
     
    public MountianCycle(String color)
    {
        this.color = color;
    }
    //Method to display both Cycle and MountianCycle class attributes
    public void ride()
    {
        /**The below code will throw error as we are 
        accessing the private member directly**/
       /* System.out.println("Number of Gear : \""+gear+"\"");
        System.out.println("Speed of Cycle : \""+speed+"\"");*/
        System.out.println("Color of Cycle : \""+color+"\"");
    }
 }
public class InheritanceTest 
{
    public static void main(String args[]) 
    {
        //Create object of the Sub Class(MountianCycle)
        MountianCycle mb = new MountianCycle("Blue");
        /**Set the values to the Cycle class attributes through setters**/
        mb.setSpeed("66kmh");
        mb.setGear(6);
        mb.ride();
        /**Get the parent class members using public access methods getters **/
        System.out.println("Number of Gear : \""+mb.getGear()+"\"");
        System.out.println("Speed of Cycle : \""+mb.getSpeed()+"\"");
     }
}

Output :

Color of Cycle : "Blue"
Number of Gear : "6"
Speed of Cycle : "66kmh"

Use of Java Inheritance – Protected Access Modifier

A protected member of the class in different package can be accessed by the class in other package only through inheritance. Lets look into the below code

Parent.java

The Parent class belong to the package “com.javainterviewpoint.test” and has the protected member val

package com.javainterviewpoint.test;

public class Parent 
{
    protected static int val = 10;
}

Child.java

Child class belongs to the package “com.javainterviewpoint”. Even though we have imported the Parent class in our Child class, the protected member “val” will not be visible to the Child class.

package com.javainterviewpoint;

import com.javainterviewpoint.test.Parent;

public class Child 
{
    public static void main(String args[]) 
    {
        System.out.println("Value of Protected member in Parent class "+val);
     }
}

When we run the above Child class we will be getting error like “val cannot be resolved to a variable”

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	val cannot be resolved to a variable

	at com.javainterviewpoint.Child.main(Child.java:9)

The only way to make the Protected member visible to the class in the other package is through inheritance. Lets now make the child class to inherit the parent class.

package com.javainterviewpoint;

import com.javainterviewpoint.test.Parent;

public class Child extends Parent
{
    public static void main(String args[]) 
    {
        System.out.println("Value of Protected member in Parent class "+val);
     }
}

Output :

Value of Protected member in Parent class 10

Method Overriding in Java Inheritance

Method Overriding in Java is possible only when Sub class is inheriting the Super class. Lets look into the below example where both Parent and Child class will have same display() method and Child class extends Parent class.

package com.javainterviewpoint;

class Parent 
{
    public void display()
    {
        System.out.println("Parent Class display() method");
    }
}
public class Child extends Parent
{
    public void display()
    {
        System.out.println("Child class display() method");
    }
    public static void main(String args[]) 
    {
        //Parent class object to Parent reference
        Parent p = new Parent();
        p.display();
        //Child class object to Child reference
        Child c = new Child();
        c.display();
        //Child class object to Parent reference
        Parent pc = new Child();
        pc.display();
     }
}

Output :

Parent Class display() method
Child class display() method
Child class display() method

Super Keyword in Inheritance

When Sub class has inherited the Parent class then we can use the Super keyword to call the Parent class methods and constructors.

package com.javainterviewpoint;

class Parent 
{
    public Parent()
    {
        System.out.println("Parent Class Constructor");
    }
    public void display()
    {
        System.out.println("Parent Class display() method");
    }
}
public class Child extends Parent
{
    public Child()
    {
        super();
        System.out.println("Child Class Constructor");
    }
    public void display()
    {
        System.out.println("Child class display() method");
        super.display();
    }
    public static void main(String args[]) 
    {
        //Child class object to Child reference
        Child c = new Child();
        c.display();
     }
}

Output :

Parent Class Constructor
Child Class Constructor
Child class display() method
Parent Class display() method

Note :

  • While calling the Constructors of the Parent class the super() has to be the first line in the Child class constructor.
  • While calling the methods of the Parent class the super.MethodName() can be any where within the Child class method.

Other interesting articles which you may like …

  • JVM Architecture – Understanding JVM Internals
  • Object and Object Class in Java
  • Difference between JDK, JRE and JVM
  • Components of Java Development Kit (JDK)
  • What is a Class in Java with Example
  • How to open .class file in Java
  • How to Set Classpath for Java in Windows
  • ClassNotFoundException Vs NoClassDefFoundError
  • How HashMap works in Java
  • How to make a class Immutable in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of polymorphism in Java

Filed Under: Core Java, Java, OOPs Tagged With: Inheritance, Inheritance in Java, Java, Method Overriding, Use of Inheritance

Comments

  1. Alishan says

    November 12, 2017 at 3:30 pm

    very Best Website for Java Learning.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·