Java Inheritance Basic
Inheritance is a key concept in object-oriented programming and allows one class to inherit the properties and methods of another class. In Java, inheritance is implemented using the extends
keyword.
The class that is being inherited from is called the "superclass" or "parent" class, and the class that inherits from it is called the "subclass" or "child" class.
To create a subclass in Java, you use the extends
keyword followed by the name of the superclass. For example, suppose you have a Person
class and you want to create a Student
subclass that inherits from it:
kotlinpublic class Person {
// properties and methods of the Person class
}
public class Student extends Person {
// additional properties and methods of the Student class
}
The Student
class now has access to all the properties and methods of the Person
class, as well as any additional properties and methods that you define in the Student
class.
You can also override methods of the superclass in the subclass using the @Override
annotation. For example, if the Person
class has a toString
method, you can override it in the Student
class like this:
typescriptpublic class Student extends Person {
@Override
public String toString() {
// custom implementation of the toString method for the Student class
}
}
In addition to extends
, Java also supports the concept of "interfaces", which allow classes to define a set of methods that must be implemented by any class that implements the interface. A class can implement multiple interfaces, but can only extend one superclass.
Comments
Post a Comment