"Java Programming Logic" Chapter 4 Class Inheritance

Chapter 4 Class Inheritance

Computer programs often use the inheritance relationship between classes to represent the classification relationship of object time. In the inheritance relationship, there are parent classes and child classes . The parent class is also called the base class, and the child class is also called the derived class. The subclass inherits the properties and behaviors of the parent class, and the subclass can also increase the unique properties and behaviors of the subclass. For some behaviors of the parent class, the implementation of the child class may not be exactly the same as the parent class.

On the one hand, the use of inheritance can reuse code, public attributes and behaviors can be placed in the parent class, and the subclass only needs to pay attention to the unique part of the subclass. On the other hand, objects of different sub-categories can be handled uniformly more easily.

4.1 Basic concepts

In Java, all classes have a parent class, Object by default.

Object attributes are not defined, but the definition of a number of methods, such as toString(), getClass, hashCode()and the like.

Java inheritance has the following requirements.

  • Java uses extendskeywords to express inheritance relationships, and a class can only have one parent class at most.
  • The subclass cannot access the privateproperties and methods of the parent class .
  • In addition to the subclass inherits privateall the properties and methods of the parent class outside.

Subclasses can override the methods of the parent class to reflect their own different implementations. Rewriting is actually defining the same method in the subclass as the parent class, and then reimplementing it. When rewriting a method, you need to add it before the rewritten method @Overrideto indicate that this method of the subclass is a method of the rewritten parent class.

In newthe process of using the created object, the construction method of the parent class will also be executed, and it takes precedence over the call of the construction method of the child class. If you need to explicitly call the constructor of the parent class, you need to use superkeywords. superThe method of use is the thissame, except that it superrepresents the parent class. However, thisreferencing an object actually exists, can be used as a function parameter, and can be used as a return value. But it superis just a keyword and cannot be used as a parameter or return value. Its function is only to tell the compiler to access the relevant variables and methods of the parent class.

One advantage of using inheritance is to uniformly handle objects of different subtypes through a parent class variable. This is called polymorphism , and we can assign a subclass variable to a superclass variable if the superclass has multiple subclasses. At this time, when the parent class and the subclass have the same name are called through the parent class, which subclass or the method of the parent class is called is determined by the runtime, which is called dynamic binding.

Polymorphism and dynamic binding are an important way of thinking in computer programs, so that programs that manipulate objects do not need to pay attention to the actual types of objects, so that different objects can be processed uniformly , but the unique behavior of each object can be realized .

4.2 Details of inheritance

In the process of subclass creation, the construction method of the parent class must be called. At this point, the subclass can supercall the construction method of the parent class. If the subclass does not pass the supercall, the compiler will automatically call the default construction method of the parent class. If the parent class does not have the default construction method, a compilation error will occur.

If a method that can be overridden by a subclass is called in a method of the parent class, unexpected results may occur. Because if the subclass calls a method A of the parent class, and A will call the method B that has been overridden by the subclass. Even if A is a method of the parent class, the B called by A is no longer a method of the parent class, but a method that has been overridden. However, this situation in the construction method is a bad practice and is easy to cause confusion, so the construction method should only call the privatemethod.

The subclass can override the non- privatemethods of the parent class , which will be dynamically bound when called, but for instance variables, static methods, static variables and private methods, if the variables and methods of the subclass and the parent class have the same name, then The static binding is performed when called. That is to say, if it is called through a parent class variable, the method and property of the parent class are called, and if it is called through a child class variable, then the method and property of the subclass are called. For the dynamic binding of instance methods, we can call the instance method of the subclass through a parent class variable. As for which method, it can be dynamically determined at runtime.

Similar to rewriting is overloading . Overloading is just that the method name is the same but the function signature (number of parameters, type or order) is different, and the rewriting requires that everything except the method definition is exactly the same. When there are multiple overloaded functions, the most matching version among all overloaded versions will be selected to call according to the parameters at the time of calling. Then check the dynamic type of the variable and perform dynamic binding.

We can assign a subclass variable to a parent class variable, but whether the parent class variable can be assigned to a subclass variable depends on the dynamic type of the parent class variable. In other words, it will succeed only when the variable type referenced by the parent class variable is indeed the subclass variable to be assigned, otherwise a compilation error will occur. You can use instanceofkeywords to check whether a parent class variable refers to a subclass object.

public boolean canCast(Base b) {
    
    
    // child是子类
    return b instanceof Child;
}

protectedThe keyword indicates that although the property or method cannot be accessed externally, it can be accessed by subclasses or by other classes in the same package, regardless of whether other classes are subclasses of this class. protecedOne of the common application scenarios is the template method.

When overriding methods, subclass methods can improve but not reduce the visibility of parent methods. If the parent method is public, then the child method needs to be public; if the parent method is protected, then the child method can be protectedor it can be public.

You can use modifiers finalto prevent inheritance. If the finalmodification is a class, then this class cannot be inherited. If the finalmodification is a method of a class, then this method cannot be overridden by a subclass.

4.3 Basic principles of inheritance

In Java, the so-called class loading is to load the relevant information of the class into the memory. In Java, a class is dynamically loaded. It will be loaded when the class is used for the first time. When a class is loaded, it will check whether its parent class has been loaded, and if not, its parent class will be loaded.

When creating an object, the process is as follows

  • Allocate memory.
  • Execute static variables and static initialization code.
  • Assign default values ​​to all instance variables.
  • Execute the instance initialization code.

The allocated memory includes instance variables of this class and all parent classes, but does not include any static variables. The execution of the instance initialization code starts from the parent class, and then the initialization code of the subclass is executed. Before executing any initialization code, all instance variables have been set to default values.

When looking for an instance method to be executed, start with the actual type information of the object, and then look for the type information of the parent class when it is not found. If the inheritance level is relatively deep, and the method to be called is located in the upper parent class, it needs to go through multiple searches. Most systems use a method called a virtual method table to optimize the efficiency of the call. The so-called virtual method table is to create a table for each class when the class is loaded, recording all the dynamically bound methods and addresses of the objects of the class, but there is only one record for a method. After the subclass overrides the parent class method, only the subclass will remain.

Access to variables is statically bound.

4.4 Inheritance is a double-edged sword

Inheritance is destructive, and there are mainly the following problems.

  • Inheritance destroys encapsulation, because there may be detailed dependencies between subclasses and parent classes.
  • Inheritance does not reflect the is-arelationship.

Guess you like

Origin blog.csdn.net/NelsonCheung/article/details/109968387