In Java, inheritance is a mechanism that allows a new class to be based on an existing class. The existing class is known as the superclass or parent class, while the new class is known as the subclass or child class. The subclass inherits all the properties and methods of the superclass, and can add its own properties and methods as well.
Inheritance is achieved in Java through the use of the extends keyword. To create a subclass, you simply specify the superclass that you want to inherit from, and add any additional properties and methods that you need.
Here’s an example Java program that demonstrates inheritance:
public class Animal {
private String species;
private int age;
public Animal(String species, int age) {
this.species = species;
this.age = age;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Dog extends Animal {
private String breed;
public Dog(String species, int age, String breed) {
super(species, age);
this.breed = breed;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog("Canine", 5, "Labrador Retriever");
System.out.println("My dog is a " + myDog.getBreed()
+ " and is " + myDog.getAge() + " years old.");
}
}
In this program, we define a class called Animal that represents an animal. The Animal class has two instance variables (species and age) that represent the state of an animal, and getter and setter methods for each variable.
We then define a subclass called Dog that extends the Animal class. The Dog class has an additional instance variable (breed) that represents the breed of a dog, and a getter and setter method for the breed variable.
Finally, we create an object of the Dog class called myDog, with a species value of "Canine", an age value of 5, and a breed value of "Labrador Retriever". We then use the getBreed and getAge methods of the myDog object to print a message to the console.
When we run this program, it outputs the following:
My dog is a Labrador Retriever and is 5 years old.
This shows how we can use inheritance in Java to create a new class (Dog) based on an existing class (Animal) and add additional properties and methods to it. By inheriting from the Animal class, the Dog class automatically gets access to the species and age properties and methods, without having to redefine them. This makes our code more efficient and easier to maintain.