An analysis of the differences between overloading overwriting and hiding in Java
- 2020-04-01 01:50:57
- OfStack
Overload: multiple functions of the same name with the same method name but different arguments
Note: 1. Different parameters mean at least one different parameter type, number and order
2. Return values and exceptions, as well as access modifiers, cannot be overridden (because for anonymous calls, there will be ambiguity, eg:void a() and int a(), if called a(), there will be ambiguity)
The 3. Main method can also be overloaded
Overrides: a subclass overrides a method in a parent class, requiring that the method name and parameter type be exactly the same (parameters cannot be subclasses), that the return value and exception are smaller or the same (that is, a subclass of the parent class), and that the access modifier be larger or the same
Two is one and two is one
Note: a subclass instance method cannot override a parent's static method. A static method of a subclass also cannot override an instance method of a parent class (compile times error), concluding that a method cannot cross-override
Hide: when a parent class and a subclass have properties or methods with the same name, the parent class's properties or methods with the same name are no longer there
Note: when hiding occurs, what type of class is declared to invoke the corresponding class's properties or methods without dynamic binding
There is only one form of method hiding, which is that the parent class and the subclass have the same static methods
Properties can only be hidden, not overridden
Subclass instance variables/static variables can hide the instance/static variables of the parent class, summarized as variables can be cross-hidden
The difference between hiding and overwriting:
Properties that are hidden from the parent class after the child class is cast to the parent class
The overridden method calls the subclass's own method after the subclass is cast to its parent
Because coverage is dynamic binding, it is constrained by RTTI(run time type identification, runtime type checking), and hiding is not constrained by RTTI. It is concluded that RTTI is only for covering, not for hiding
Special case:
1. The final modification properties can be hidden, but cannot be assigned, namely cannot use = to assign a value, said final attribute cannot be modified online, this statement is not accurate, because for a reference type variable with the final after modification, it just can't be pointing to other objects, but it can change its value, can use ArrayList test, final properties can be initialized at run time, but can't afford not to initialize the statement
2. Final modified methods cannot be overridden and can be overridden
3. Classes that are final cannot be inherited
4. The private method adds final implicitly