Monday, 1 May 2023

What is Inheritance in Java? with example.



Inheritance Is A Fundamental Concept In Object-oriented Programming That Allows You To Create New Classes Based On Existing Ones. Inheritance Enables You To Reuse Code And Extend The Functionality Of Existing Classes. In Java, You Can Implement Inheritance Using The "Extends" Keyword. Here's An Example Of Inheritance In Java:


```

// Parent class

class Vehicle {

   private String make;

   private String model;

   private int year;


   public Vehicle(String make, String model, int year) {

      this.make = make;

      this.model = model;

      this.year = year;

   }


   public void start() {

      System.out.println("Vehicle started.");

   }

}


// Child class

class Car extends Vehicle {

   private int numDoors;


   public Car(String make, String model, int year, int numDoors) {

      super(make, model, year);

      this.numDoors = numDoors;

   }


   public void accelerate() {

      System.out.println("Car accelerated.");

   }

}


// Main class

class Main {

   public static void main(String[] args) {

      Car myCar = new Car("Honda", "Civic", 2021, 4);

      myCar.start(); // Output: Vehicle started.

      myCar.accelerate(); // Output: Car accelerated.

   }

}

```


In The Example Above, We Have A Parent Class Called "Vehicle" That Has Three Private Instance Variables: "Make", "Model", And "Year". The Class Also Has A Constructor And A Method Called "Start". 


The Child Class Called "Car" Extends The Parent Class "Vehicle". The Child Class Has An Additional Private Instance Variable Called "Numdoors" And A Constructor. It Also Has A Method Called "Accelerate".


In The Main Class, We Create An Object Of The "Car" Class And Call The "Start" And "Accelerate" Methods. The "Start" Method Is Inherited From The Parent Class, While The "Accelerate" Method Is Specific To The Child Class.


This Is Just A Simple Example Of Inheritance In Java, But It Demonstrates The Basic Concept Of Creating New Classes Based On Existing Ones. By Using Inheritance, You Can Build More Complex Class Hierarchies And Reuse Code, Making Your Programs More Efficient And Easier To Maintain.

No comments:

Post a Comment

What is Java Permutation and Combination Program?

Here's A Java Program That Calculates Permutations And Combinations: ```Java Import Java.Util.Scanner; Public Class Permutationcombinati...