Working with Inheritance

  • Eclipse: Oxygen
  • Java: 1.8

Inheritance

Inheritance is the process of defining a new class based on an existing class where a child class acquires the properties of the parent class. For using the properties of a class (superclass) we need to create a class(subclass) and then use the ‘extends’ keyword to use the common property in the extended sub class. This is the basic functionality of inheritance to reduce the redundant code.

Extend Keyword

Extend keyword is used to inherit the properties of the class.

Let us consider the following program that demonstrates that inherits some properties and methods in child class from the parent class.

 

Step 1: Let us create a class vehicle where we declare and define common properties and methods. Here, vehicle is a super-class.

Step 2: We create a child class for example Bike, Car, Truck class which extends the above class Vehicle. Here all these classes use specific properties. You can observe these specific properties in blow statement.

Bike class

Car class

Truck class

Step 3: We create a class called Demo for creating an object of Bike class and initialize the variable with string “short”.

Step 4: We can access the methods from super-class in the sub-class as if they are in the same class. e.g We create an object of bike class, which access the engine property of vehicle class.

Output

Petrol

We have defined the properties. Now we will learn how default constructors of Superclass are called automatically in the Subclass. Here in this post, we will learn how to inherit default constructor from superclass to subclass.

For example, let’s return to the Vehicle example we used in the previous section and show two related classes that define the same method:

We define the String property “lights” as private in the parent class Vehicle. However, when I display the property lights without initializing and run the program we will receive an exception. I am not allowed to define “lights” as public. Why?  Because lights entities are the private entities we won’t access this private entity in the child class.

Output

Exception in thread “main” java.lang.Error: Unresolved compilation problem:

      The field Vehicle.lights is not visible

     at org.studyeasy.Demo.main(Demo.java:11)

Access the private variables in the child class

In the following code, to access the private variables in java. We have provided a default constructor and parameterize constructor. In default constructor, we have initialized some default properties. You can provide public getter and setter methods to access or change the value of the private member variables. In the following example, we have already initialized the default value so no need to provide setter we will provide the only getter. So we are able to access the private method from the parent class.

Vehicle Class

Bike Class

We have initialized the “handle” property in the default constructor. By using super keyword we called the default constructor of parent (Vehicle) class.

Demo Class

By accessing the getHandle() and getEngine() method we display the properties values of bike class.

Output:

short

petrol

 Note: In this program, we are making use of default constructor. In the next tutorial, we will make use of the parameterized constructor.

We have learned how the default constructors of Superclass are called automatically in the Subclass. Here, we will learn how to derive parameterized constructor from superclass to subclass.

Output

Handle: short

Engine type: petrol

Parent class parameterized constructor is called in child class using super ().super () should be the written in the first line inside the constructor. For example, the output of the following program is:

Output:

Steering: Power steering

Engine type: Deisel

Number of seats: 4

Fuel tank capacity: 40

Headlamp type: LED

Number of wheels: 4

Java toString() method  

In Java toString() method is used to get a String representation of an object.

We can override the object’s toString() method during implementation.  The toString() method of the Object class helps us to return values of the object, so we don’t need to write much code.

Example

In the following example, We have initialized the properties of Car using the constructor, printing the object of the car class prints the hashCode ([email protected]) values of the objects.

Output

[email protected]

Let’s see the real example of toString () method in following code. We override the toString () method with the properties that we want to display.

Output

Car [getSteering()=Power steering, getEngine()=deisel, getWheels()=4, getSeats()=4, getFueTank()=40, getLights()=LED, getClass()=class org.studyeasy.vehicles.Car, hashCode()=366712642, toString()[email protected]]

We have discussed superclasses and subclasses. Now, we will discuss method overriding.

Method overriding

The method override is used for the runtime polymorphism. It helps to define a behavior that is specific to the subclass or child class type, which means a subclass can implement a parent class based on your request.

Rules for Java Method Overriding

  • The method must have the same name as in the parent class
  • The method must be IS-A relationship(inheritance)
  • The method must have the same parameters as in the parent class.

In the following example we demonstrate method overriding, the run () method of Parent class is defined in child class with the same implementation, so output will be “Running vehicle”

Output

Car [getSteering()=Power steering, getEngine()=deisel, getWheels()=4, getSeats()=4, getFueTank()=40, getLights()=LED, getClass()=class org.studyeasy.vehicles.Car, hashCode()=366712642, toString()[email protected]]

Running vehicle

In the following example, we have defined the run method in the child class, as defined in the parent class but child class wants to specify its own implementation. The name of the method and parameter must be the same and there must be an IS-A relationship between the classes. Therefore, there is method overriding. When we execute this method, it generates “Running car” instead of “Running vehicle”.

Output

Running car

Car [getSteering()=Power steering, getEngine()=deisel, getWheels()=4, getSeats()=4, getFueTank()=40, getLights()=LED, getClass()=class org.studyeasy.vehicles.Car, hashCode()=366712642, toString()[email protected]]

Contributed by: Poonam Tomar

 

 


VIEW COURSES

Buy me a coffee!

 

PayTM QR (INDIA)

  • Get video tutorials
  • Project files set
  • Get Certified

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu