The Inheritance and override of member methods are similar to those of member variables, but they are different.
It is similar that the member variables that can be inherited are of the same type as the member methods, and the public and protected member methods of the stepfather class can be used.
The difference is that the member methods are actually overwritten. After defining the same methods as the parent class, the same methods in the parent class do not exist in the subclass.
First, determine what is the same method? The same method indicates the same method name, number of parameters, parameter type, and return value type. It is irrelevant to the parameter name.
For example, the following method is the same:
Public void setage (INT age ){...}
Public void setage (int sage ){...}
The following methods are different:
Public void setage (INT age ){...}
Public void setage (string age ){...}
Note: When a subclass overwrites the method of the parent class, the type of the returned value cannot be modified, and the access permission cannot be reduced. The following two methods are incorrect.
In the parent class:
Public int geta (){
Return;
}
Subclass:
Protected int geta () {// reduces the access permission
Return;
}
Public String geta () {// modified the return value type
Return string. valueof ();
}
The method is used to define the behavior. The override of the method is that the subclass modifies the implementation method of the behavior in the parent class. Method coverage is related to polymorphism.
If the method is not overwritten, it will be inherited directly. If it is overwritten, this method of the parent class does not exist in the subclass.
What is the result of the following question?
Package test;
Public Class Parent {
Public int A = 10;
Public int geta (){
Return;
}
}
Package test;
Public class Child extends parent {
Public int A = 20;
Public int getparenta (){
Return super.;
}
Public int getchilda (){
Return;
}
}
Package test;
Public class test {
Public static void main (string ARGs []) {
Child child = new child ();
System. Out. println (parent) Child). );
System. Out. println (child. getparenta ());
System. Out. println (child. getchilda ());
System. Out. println (child. Geta ());
}
}
View the running result:
10
10
20
10
Pay attention to the last one.
Last time: in lecture 36th, the inheritance and overwrite of member variables Next: 38th lecture on abstract classes and abstract methods Li xucheng csdn blog: Http://blog.csdn.net/javaeeteacher Invite you as a friend:Http://student.csdn.net/invite.php? U= 124362 & C = 7be8ba2b6f3b6cc5