Home > Java > Javagetting Started > How to inherit in java

How to inherit in java

(*-*)浩
Release: 2019-11-13 10:27:04
Original
3668 people have browsed it

How to inherit in java

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);
    }
}
Copy after login

Explanation of the program

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template