Inheritance is one of the fundamental concepts of object-oriented programming. In Java, inheritance allows you to create a new class based on an existing class, which inherits all the attributes and behaviors of the original class. The new class is called the subclass or child class, while the existing class is called the superclass or parent class.
To create a subclass in Java, you use the extends keyword followed by the name of the superclass:
public class Subclass extends Superclass {
// subclass body
}
The subclass can access all the non-private members (fields and methods) of the superclass, including any public or protected fields and methods. It can also define its own fields and methods, as well as override or overload the superclass methods.
Here’s an example that demonstrates how inheritance works in Java:
public class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name); // call the superclass constructor
}
@Override
public void makeSound() {
System.out.println("The dog barks");
}
public void fetch() {
System.out.println("The dog fetches a ball");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Fido");
System.out.println(dog.name); // prints "Fido"
dog.makeSound(); // prints "The dog barks"
dog.fetch(); // prints "The dog fetches a ball"
}
}
In this example, Animal is the superclass and Dog is the subclass. Dog inherits the name field and makeSound() method from Animal, and it defines its own fetch() method. The @Override annotation indicates that Dog is overriding the makeSound() method of Animal.
In the Main class, we create a Dog object and demonstrate how it can access the name, makeSound(), and fetch() methods of both Dog and Animal.
In summary, inheritance in Java allows you to create new classes based on existing classes, reuse code, and build class hierarchies. It is an essential tool for writing object-oriented programs that are modular, extensible, and easy to maintain.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.