Advertisement

Inheritance in Java

Inheritance in Java

Inheritance is a feature in object-oriented programming that allows one class to inherit properties and methods from another class. It is a way to reuse code and to establish a relationship between classes.


Here is an example of how inheritance is used in Java:

// Base class (Parent) 

class
Animal {
// Properties
    String name;
    int age;

// Constructor

public Animal(String name, int age) {
     this.name = name;
     this.age = age;
 }

// Method

public void eat() {
     System.out.println("Animal is eating.");
     }
}
// Derived class (Child)

class
Dog extends Animal {
// Properties
     String breed;
// Constructor
public Dog(String name, int age, String breed) {
     super(name, age);
    this.breed = breed;
 }
// Method
public void bark() {
     System.out.println("Dog is barking.");
 }
}


In the example above, the Dog class is derived from the Animal class, which means it inherits all the properties and methods of the Animal class. The Dog class also has its own properties (breed) and methods (bark()).


You can create an object of the Dog class like this:

Dog dog = new Dog("Max", 3, "Labrador");


The dog object has access to all the properties and methods of the Animal class, as well as the breed property and the bark() method of the Dog class.


dog.eat(); // Output: Animal is eating.
dog.bark(); // Output: Dog is barking.


Hope that helps! Do you have any other questions about inheritance in Java?






Post a Comment

1 Comments