This website includes Education Information like a programming language, job interview question, general knowledge.mathematics

Education log

PageNavi Results No.

Ads

Sunday, September 17, 2023

what is inheritance in java with example

 what is inheritance in java  with example


Introduce:

Inheritance in Java is a mechanism that allows programmers to create new classes that inherit the properties and behaviors of existing classes. This can be done by using the extends keyword to specify the class that is being inherited from. The class that is being inherited from is called the superclass, and the class that is inheriting from it is called the subclass.

There are two types of inheritance in Java: single inheritance and multiple inheritance. Single inheritance is the most common type of inheritance and allows a class to inherit from only one superclass. Multiple inheritance allows a class to inherit from multiple superclasses.



What is inheritance in Java explain?


Inheritance in Java is a concept that acquires the properties from one class to other classes; for example, the relationship between father and son. Inheritance in Java is a process of acquiring all the behaviours of a parent object.


Example Inheritance  in java:



Class PetAnimal {


  // field and method of the parent class

  String name;

  public void eat() {

    System.out.println("I can eat");

  }

}


// inherit from PetAnimal

class Dog extends PetAnimal {


  // new method in subclass

  public void display() {

    System.out.println("My name is " + name);

  }

}


class Main {

  public static void main(String[] args) {


    // create an object of the subclass

    Dog labrador = new Dog();


    // access field of superclass

    labrador.name = "Rohu";

    labrador.display();


    // call method of superclass

    // using object of subclass

    labrador.eat();


  }

}

No comments:

Post a Comment