An example examines the difference between overloading and overwriting in Java

  • 2020-04-01 03:26:07
  • OfStack

This article analyzes the difference between overloading and overwriting in Java in detail with an example.

I. Overloading:

(1) method overloading is a means for classes to handle different types of data in a uniform way. Multiple functions of the same name exist at the same time, with different parameters/types.
Overloading is a manifestation of polymorphism in a class.

(2) method overloading in Java means that multiple methods can be created in a class with the same name but different parameters and different definitions.
Polymorphism is when methods are called to determine which method to use by the number and type of different arguments passed to them.

(3) when overloaded, the method name should be the same, but the parameter type and number are different, and the return value type can be the same or different. The return type cannot be used as a distinguishing criterion for overloaded functions.

Here's an example of overloading:


package c04.answer;//This is a package name
//This is the first programming method of the program, creating an instance of the Dog class in the main method, and then calling different bark methods in the constructor of the Dog class with this keyword.
 Different overloaded methods bark Is distinguished according to its parameter type. 
//Note: the compiler prohibits calling constructors anywhere except the constructor.
package c04.answer;
public class Dog {
Dog()
{
this.bark();
}
void bark()//The bark() method is an overloaded method
{
System.out.println("no barking!");
this.bark("female", 3.4);
}
void bark(String m,double l)//Note: overloaded methods return the same value,
{
System.out.println("a barking dog!");
this.bark(5, "China");
}
void bark(int a,String n)//Overloaded methods cannot be distinguished by return values, but only by parameter types and class names
{
System.out.println("a howling dog");
}
public static void main(String[] args)
{
Dog dog = new Dog();
//dog.bark(); [Page]
//dog.bark("male", "yellow");
//dog.bark(5, "China");

Second, the rewrite (Overriding)

(1) polymorphism between parent class and subclass, and redefine the function of parent class. If a method defined in a subclass and its parent class have the same name and parameters, we say that this method be rewritten (Overriding). A subclass can inherit a method from a parent class without having to rewrite the same method.
Sometimes, however, a subclass doesn't want to inherit the parent's methods intact, but instead wants to make changes that require method overrides.
Method overrides are also called method overrides.

(2) if a method in a subclass has the same method name, return type, and parameter table as a method in a parent class, the new method overrides the original method.
If you need methods that are native to the parent class, you can use the super keyword, which refers to the parent of the current class.

(3) the access modification permission of the subclass function cannot be less than that of the parent class;

Here is an example of rewriting:

Concept: a mechanism for calling an object's methods.

The inside story of dynamic binding:

1. The compiler checks the declared object type and method name to get all candidate methods. Try commenting out the test of the Base class above, and the compilation won't pass.
2. Overload decision: the compiler checks the parameter types of method calls and selects the unique one from the candidate method (with implicit type conversions).
If the compiler finds more than one or none, the compiler reports an error. Try commenting out the test(byte b) of the Base class above, and the result is 1, 1.
3. If the method type is priavte static final and Java is statically compiled, the compiler knows exactly where to call it
A method.
4. When a program runs and calls a method using dynamic binding, the virtual machine must call the version of the method that matches the actual type of the object.
In the example, b is pointing to the actual type is TestOverriding, so b.t est (0) call subclasses of the test.
However, the subclass does not override test(byte b), so b.est ((byte)0) calls test(byte b) of the parent class.
If the parent's (byte b) is commented out, the second implicit type is converted to int, and the subclass's test(int I) is called.

Iii. Learning summary

Polymorphism is a feature of object-oriented programming that has nothing to do with methods,
In short, the same method can make different processing according to the input data, that is, the method
Overloading -- with different parameter lists (static polymorphism)
And when a subclass inherits the same method from the parent class, same input data, but responds differently to the parent class, you override the parent class method,
That is, override the method in a subclass -- same parameter, different implementation (dynamic polymorphism)

OOP has three features: inheritance, polymorphism, and encapsulation.


public class Base
{
void test(int i)
{
System.out.print(i);
}
void test(byte b)
{
System.out.print(b);
}
}
public class TestOverriding extends Base
{
void test(int i)
{
i++;
System.out.println(i);
}
public static void main(String[]agrs)
{
Base b=new TestOverriding();
b.test(0)
b.test((byte)0)
}
}

The output is 1, 0, which is the result of dynamic binding at runtime.

The main advantage of overrides is the ability to define characteristics specific to a subclass:


publicclassFather{
publicvoidspeak(){
System.out.println(Father);
}
}
publicclassSonextendsFather{
publicvoidspeak(){
System.out.println("son");
}
}

This is also called polymorphism, and overriding methods can only exist in inherited relationships, and overriding methods can only override methods that are not private from their parent class.
When the method of Father speak() in the above example is private, the Son class cannot override the method of Father speak(). At this time, the method of Son speak() is equivalent to a speak() method defined in the Son class.
When the Father speak() method is final, the Son class cannot override the Father speak() method at all, regardless of whether the method is public,protected or modified by default.
When you try to compile code, the compiler reports an error. Ex. :


publicclassFather{
finalpublicvoidspeak(){
System.out.println("Father");
}
}
publicclassSonextendsFather{
publicvoidspeak(){
System.out.println("son");
}
}//The compiler will report an error;

When the Father class speak() method is modified by default, it can only be overridden in the same package by its subclass, and cannot be overridden if it is not in the same package.

When the Father class speak() method is protoeted, it is not only overridden by its subclass in the same package, it can also be overridden by subclasses of different packages.

Rewrite the rules of the method:

1. The argument list must be exactly the same as the method being overridden, otherwise it cannot be overridden but overridden.
2. The type returned must always be the same as the method being overridden, or it cannot be overridden but overridden.
3. The limit of access modifier must be greater than the access modifier of the overridden method (public> Protected> Default> Private)
4. The rewrite method must not throw a new check exception or a broader check exception than the one declared by the rewrite method. Such as:
A method of the parent class declares a check Exception IOException. If you override this method, you cannot throw an Exception. You can only throw a subclass Exception of IOException, and you can throw a non-check Exception.

And overloaded rules:

1. There must be a different parameter list;
2, there can be no scold return type, as long as the parameter list is different;
3, there can be different access modifiers;
4. Different exceptions can be thrown;

The difference between overwriting and overloading is:

Override polymorphism works because calling overloaded methods can greatly reduce the amount of code input, and the same method name can have different functions or return values simply by passing different arguments into it.
Overrides and overloads, which can be used to design a clean and concise class, can play an important role in writing code.


Related articles: