The inheritance according to our Chinese popular understanding is does not need to pay the effort, obtains other people's ability or the asset, for example inherits the father's property, inherits the father's expression ability, inherits the father's appearance and so on. Inheritance within a class can be understood without the need to re-develop the code, you can reuse the parent class method and domain.
In the inheritance relationship, you can be divided into the parent class and the subclass, the subclass inherits the parent class, the subclass has the same method and the property as the parent class, but the subclass can also have its own external methods and properties, like you inherit all the family property of the parents, but also can have their own assets. All inheritance is a is-a relationship. Java class inheritance uses extends to express inheritance relationships. For example:
Class Manager extends emloyee{}
In addition to inheriting the parent class method, subclasses can override the parent class method and call this override of the parent method. It is worth noting that when overriding a method, the return type of the subclass override method is allowed to be defined as a subtype of the original type. For example:
public class employee{public Employee GetBuddy () {...}} Parent class Employeepublic class Manager extends Employee {public Manager GetBuddy () {...} Subclass override GetBuddy method that returns a subtype of the original type}
How is inheritance implemented, and how is the internal implementation principle?
1, each object when invoking the method, in fact, the method has an implicit parameter, for example:
Manager mg=new Manager (); Mg.getbuddy (); GetBuddy actually has an implicit parameter, the current object reference, execution will be the object reference into the Mg.getbuddy (MG);
2, each class, the virtual machine pre-creates a method table for each class, which is used to record the memory address of all methods. When calling the method, go directly to the method corresponding to the memory address to execute, if it is a simple inheritance, equivalent to the default to create a subclass of a class like a method table.
For example:
Employee:getname->employee:getname () Getbuddy->employee:getbuddy () Manager:getname->employee:getname () Getbuddy->manager:getbuddy ()
Therefore, when a subclass method is called for a different subclass object, the address of the method is queried from the subclass method table, and if the subclass overrides the parent class method, the address of the corresponding method is also modified to implement polymorphism.
--How to prevent inheritance:
Final, if the class is defined as final, then the class cannot be inherited by another class, and it is worth noting that if the class is defined as final, its method is automatically defined as final, but the domain is not automatically defined as final.
Java Core Technology Learning notes-inheritance