Method overloads:
Java's method overloading is that you can create multiple methods in a class that can have the same name , but must have different parameters , that is, the number of arguments, or the type of the parameter is different. Methods are invoked by the different number and type of arguments passed to them to determine which method to use
Example code:
public class Test {
No return value has an int shape parameter
void receive (int i) {
System.out.println ("i=" +i);
}
No return value, with float-shaped parameters
void receive (float f) {
System.out.println ("f=" +f);
}
No return value, string-shaped argument
void receive (String s) {
System.out.println ("s=" +s);
}
public static void Main (String [] args) {
Test m = new test ();
M.receive (1234);
M.receive (56.78f);
M.receive ("Method overloading");
}
}
Attention:
Java's method overloading requires that a method with the same name must have a different parameter table, and that only the return type is different is not sufficient to distinguish between two overloads of a method.
Method overrides:
In Java and some other advanced object-oriented programming languages, subclasses can inherit methods from the parent class without having to rewrite the same method . But sometimes subclasses do not want to inherit the parent class's methods, but want to make some changes , which requires a method of rewriting. Method overrides are also called method overrides.
Example code:
Package text;
public class test{
public static void Main (string[] args) {
New Derived ();
}
}
Class base{
private int i=2;
Public Base () {
Display ();
}
public void display () {
System.out.println (i);
}
}
Class Derived extends base{
private int i=22;
Public Derived () {
i = 222;
}
public void display () {
System.out.println (i);
}
}
Super Keyword:
If a method in a subclass has the same method name, return type, and parameter table as a method in the parent class, the new method overwrites the original method. If you need a method from the parent class, you can use the Super keyword, which references the parent class of the current class.
Summarize:
Method overloads:
1. Must have a different parameter list;
2. You can have different return types, as long as the parameters are different.
3. You can have different access modifiers.
Method overrides:
1. The parameter list must be exactly the same as the overridden method, otherwise it cannot be called overridden but overloaded.
2. The return type must be the same.
3. The restrictions on access modifiers must be greater than the access modifiers of the overridden method (Public>protected>default>private)
4. The main advantage of method rewriting is the ability to define characteristics that are unique to a subclass. This is also the manifestation of polymorphism.
Generalization of Java method overloading and rewriting