Summarize overloads and overrides
Define multiple ** different ** methods with the same name but ** signature **. → Even if the name is the same, ** the method is different **
** * What is signature ** -Method name -Argument list type -Number of arguments -Argument order
** [Things not to consider when overloading] ** ・ Difference in return value -Variable name of the argument -Differences in access modifiers
Example)
int price(int a, double b){
return a * b;
}
[Overloading pattern]
double price(int a){ //Since it is treated as a separate method, there is no problem even if the return value is changed. Overloaded because the signatures are different
//processing
}
int price(double a, int b){ //Argument order reversed → overload
//processing
}
[** It is also possible to overload methods ** with final **]
final void price(){
//processing
}
void prince(int a){ //The final method can also be overloaded! Because it is treated as another method.
//processing
}
[Pattern that does not cause overload]
int price(int product, double tax){ //The argument name is not a signature. Does not overload
//processing
}
When you ** inherit ** a parent class ** and declare a ** child class **, you must ** overwrite the members of the parent class with the child class **.
** [Override conditions] ** ・ The signature is the same -** Return type ** must be ** same type ** or ** subclass type ** as a member of parent class -Specify the ** access modifier ** that is ** the same as or ** looser ** than the member of the parent class. -The member of the parent class does not have ** final **
Example)
class Infant{
protected void talk(){
System.out.println("Ogyaa");
}
}
[Patterns that can be overridden]
class Adult extends Infant {
public void talk(){ //Loose access modifiers than the parent class talk method
System.out.println("Hello");
}
}
[Patterns that cannot be overridden]
class Adult extends Infant {
void talk(){ //More stringent access modifiers than the parent class talk method
System.out.println("Hello");
}
}
class Adult extends Infant {
void talk(String a){ //Signature different from the talk method of the parent class (overload)
System.out.println("Hello" + a);
}
}
Recommended Posts