Java inheritance

Posted in Java Inheritance By Raj On November 26, 2017

 

If you want to re-use fields and methods of the parent class in the child class then you can go for inheritance, the main advantage you will get here is re-usability, you can take out all common methods which you feel are going to be re-used and keep it in parent class

The classes which are derived from the other class will have access to all methods and fields so, you do not need to repeat same methods in the child classes

The class which is derived from other class is called a child class or subclass, the class from which the subclass is derived is called a parent class

You need to consider below things before choosing inheritance

  • The methods or classes which are declared with private, static and final keywords cannot be overridden
  • Code reusability: if you have common functionalities which you feel like you can re-use in other classes then you can go for an inheritance, but you need to think about the relationship between a parent class and child class, is the child class IS-A parent class? if so then you can very well use inheritance ex: scooter IS-A motorcycle
  • You can override parent class methods in child class by using method overriding

What can you access in the child class?

You can access public and protected methods in the child class, but you can not access private methods in the child class

If the public or protected methods which are in the parent class are accessing private fields then you can access private fields only when you call those public or protected methods

You need to use super keyword to access parent class method’s and fields

There are three types of java inheritance

  • Single inheritance
  • Multilevel inheritance
  • Hierarchical inheritance

Syntax: Java Inheritance

An example of Java Inheritance

java-inheritance

Java Inheritance Code: parent class

The below java parent class has two fields and three methods, the maxSpeed is a private field so, you can not access this directly in the child class but you can access this using method which is a getMaxSpeed()

Child class

If you see the below code we can access no of gears in the child class because it is a public field and if you want to override parent class method in the child class you can do that also, refer an article java method overriding for more information

Test Inheritance code

Output:

If you are looking for Java Inheritance types then I would recommend you to read my other article which is on Java Inheritance types and you can also download code