Inheritance is the relationship between classes. It is a very simple and intuitive concept, similar to inheritance in the real world (for example, a son inherits his father's property).
Inheritance can be understood as the process by which one class obtains methods and properties from another class. If class B inherits from class A, then B has A's methods and properties.
Inheritance uses the extends keyword. # Teacher, it also has name, age, height attributes and say() method. In addition, it is necessary to add school, seniority, subject attributes and lecturing() method. What should I do? Do we need to redefine a class?
It is completely unnecessary. You can inherit the members of the People class first and then add your own members, for example:class People{
String name;
int age;
int height;
void say(){
System.out.println("我的名字是 " + name + ",年龄是 " + age + ",身高是 " + height);
}
}
Although the name and age variables are not defined in Teacher, they have been defined in People and can be used directly. Teacher is a subclass of People, and People is the parent class of Teacher class.
Subclasses can override parent class methods. Subclasses can inherit all members of the parent class except private ones.
Constructor methods cannot be inherited.
Inheritance is a great advancement in maintenance and reliability. If changes are made in the People class, the Teacher class is automatically modified without any work on the part of the programmer other than compiling it.
Single inheritance: Java allows a class to inherit only one other class, that is, a class can only have one parent class. This restriction is called single inheritance. You will learn the concept of interface later. Interface allows multiple inheritance.
The above is the detailed content of How to inherit in java. For more information, please follow other related articles on the PHP Chinese website!