[Javase Study Notes]-9.2 single inheritance and multi-Inheritance
In this section, we will look at the single inheritance and multi-inheritance in java.
In java, single inheritance is supported, and multiple inheritance is not supported directly.But the multi-inheritance in C ++ is improved.
So what is single inheritance and multi-inheritance?
Single inheritance: a subclass can only have one direct parent class.
Multi-inheritance: a subclass can have multiple direct parent classes. This is not allowed in java.
Why not? Let's look at an example:
class A{void method(){System.out.println("a");}}class B{void method(){System.out.println("b");}}class C extends A,B{}For the above situation, if we call the method of the C object, there will be an uncertainty error, and java also makes improvements based on this problem, so that it does not directly support multi-inheritance.
So we can see that the reason Why java does not directly support multi-inheritance is:When multiple classes have the same members, the call uncertainty is generated.
The java language also supports multi-inheritance.
For example, the following example shows multi-inheritance:
class A{}class B extends A{}class C extends B{}This is the form of Multi-inheritance. For the above inheritance, there is an inheritance system. In this inheritance system, A is the top class, and C is the Child class.
From the inheritance system above, we can easily see that A implements the most basic and basic functions.
So how should we use this inheritance system in actual development?
Step 1: view the top-level classes in the system (here is A) to learn about the basic functions of the system.
Step 2: create the most subclass object in the system (here is C) to use the function.
Through the above two steps, we can use an inheritance system as needed.
We have been talking about inheritance in these two sections. In 9.1, we also mentioned that inheritance can improve code reusability, but we mustNote: do not define inheritance to improve code reusability.
Why? Let's look at the following example:
class A{void method1(){}void method2(){}}class B{void method1(){}void method3(){}}We found that both classes have the method1 method, so we inherit to improve reusability:
class A{void method1(){}void method2(){}}class B extends A{void method3(){}}The method1 method does exist in Class B and can inherit the method2 method at the same time. However, the method2 method is not actually a method in Class B, which leads to a problem.
This makes it necessary to clarify when to define inheritance:When there is a relation between the class and the class, the inheritance is defined..
So what is the relationship? For example, if X is one of Y, that is, X belongs to Y, It is a link.
The link is as follows:Is a link.
So when we find that two classes are in an is a relation, we can define inheritance.