Inheritance in Java OOP – Code Example 1

In our previous post we learned how to create classes and objects by using code example. In this post we will learn inheritance which is another important object oriented programming (OOP) concept. Inheritance in Java is like a parent child relationship. As child inherit some properties or behaviors from parents, similarly in inheritance (OOP Concept) a child class can inherit properties and methods from parent class.

Following simple code example explains the inheritance concepts in Java programming. This code consists of 3 Java classes, main class (LearningInheritance.java), parent class (Vehicle.java) and child class (Car.java). Create a new project in netbeans (java development IDE) with the name of LearningInheritance. Then create 2 more classes named as Vehicle and Car in your project. Following is the code example to understand inheritance.


// Code for Car Class (child class)

package learninginheritance;

public class Car extends Vehicle {
   int no_of_doors;

   public void setNoOfDoors(int d){
      no_of_doors = d;
   }

   public void getNoOfDoors(){
      System.out.printf("No of doors are: %d\n", no_of_doors);
   }
}

// Code for Vehicle Class (parent class)

package learninginheritance;

public class Vehicle {
   int modelYear;
   int no_of_tires;

   public void setModelYear(int my){
      modelYear = my;
   }

   public void getModelYear(){
      System.out.printf("Model Year of the car is: %d\n", modelYear);
   }

   public void setNoOfTires(int n_o_t){
      no_of_tires = n_o_t;
   }

   public void getNoOfTires(){
      System.out.printf("Number of Tires are: %d\n", no_of_tires);
   }

}

// Code for LearningInheritance Class (main class)

package learninginheritance;

public class LearningInheritance {

   public static void main(String[] args) {
      Car myCar = new Car(); // created object of Car class which is child class
      myCar.setNoOfDoors(4); // defined number of doors for Car object
      myCar.getNoOfDoors(); // called a method of Car class which is child class, to get number of doors
      myCar.setNoOfTires(4); // defined number of tires for Car object
      myCar.getNoOfTires(); // called a method of Vehicle class which is parent class, to get number of tires
      myCar.setModelYear(2015); // defined model year for Car object
      myCar.getModelYear(); // called a method of Vehicle class which is parent class
   }

}

Output:

inheritance in java

 

One Reply to “Inheritance in Java OOP – Code Example 1”

Leave a Reply

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