Java Inheritance: A Brief Introduction
Java is an object-oriented programming language that allows developers to create classes and objects to encapsulate data and functionality. One of the key features of object-oriented programming is inheritance, which allows developers to create new classes that are based on existing classes. In this article, we will explore the concept of inheritance in Java and provide some sample code to illustrate its use.
What is Inheritance?
Inheritance is a mechanism by which a new class is created based on an existing class. The new class, called the subclass, inherits all the properties and methods of the existing class, called the superclass. The subclass can then add new properties and methods, or override the behavior of the inherited methods. This allows developers to reuse code and create classes that are closely related to existing ones.
Inheritance in Java
In Java, inheritance is implemented using the keyword extends. To create a subclass that inherits from a superclass, you simply include the keyword extends, followed by the name of the superclass, in the class declaration. Here's an example:
public class oldCar {
public void drive() {
System.out.println("Drive");
}
}
public class NewCar extends oldCar {
public void brek() {
System.out.println("break");
}
}
In this example, the NewCar class is a subclass of the oldCar class. The NewCar class inherits the drive() method from the oldCar class, and adds a new method, brek(). This allows us to create instances of the NewCAr class that can both drive and brek.
Super Keyword
Sometimes, you may want to call a method in the superclass from a subclass. This can be done using the super keyword. The super keyword is used to call a method in the superclass, or to refer to a property or method in the superclass. Here's an example:
public class oldCar {
public void drive() {
System.out.println("Can drive");
}
}
public class New extends oldCar {
public void Drive() {
super.Drive();
System.out.println(" with Autopilot");
}
}
In this example, the NewCar class calls the drive() method in the oldCar class using the super keyword. This allows us to reuse the behavior of the drive() method from the superclass, while still adding our own behavior in the subclass.
Conclusion
Inheritance is a powerful feature of Java that allows developers to reuse code and create new classes based on existing ones. In Java, inheritance is implemented using the extends keyword, and allows subclasses to inherit properties and methods from their superclass. By understanding inheritance in Java, you can write more organized, efficient, and maintainable code.
No comments:
Post a Comment