Home  >  Article  >  Java  >  What is inheritance?

What is inheritance?

零下一度
零下一度Original
2017-07-23 16:56:021823browse

1. What is inheritance?

A mechanism that enables one class to have all the public properties and behaviors of another class.

2. The purpose of inheritance

If a class has all the behaviors and attributes of another class, and the number of these attributes and behaviors is large , and is shared by other classes. You can define this class as a subclass to inherit another class to achieve code reuse.

3. The impact of inheritance

The subclass has the non-private methods and properties of the parent class.

4. Restrictions on inheritance

  • # Constructor method: There is a default no-argument constructor in any class method, once a parameterized constructor is explicitly created, the default parameterless constructor is cleared. The parameterless constructor of the subclass calls the parameterless constructor of the parent class by default. If there is no parameterless constructor in the parent class, compilation will not pass. Supplement: There are constructors in abstract classes, but there are no constructors in interfaces. Initialize member variables first, then call the constructor.

  • # Single inheritance: In Java, a class can only inherit one parent class through the extends keyword.

  • # Method Override: Reference.

  • Coupling degree: The subclass inherits the parent class. The subclass has a greater dependence on the parent class. Changes in the parent class have a greater impact on the subclass. big.

5. Use conditions

#Because a class has only one inheritance opportunity, and inheritance will increase the degree of coupling, out of In order to maintain inheritance opportunities and reduce coupling, only consider using inheritance when one class has many methods in common with another class. Otherwise, you can consider implementing an interface or adopting a design pattern, such as the decorator pattern.

6. Interface inheritance

An interface can inherit multiple interfaces, so that it has abstract methods of other interfaces, and does not need to implement these itself. Inherited abstract methods.

The above is the detailed content of What is inheritance?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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