Analysis of the difference between overloading and overriding in Java by example _java

Source: Internet
Author: User
Tags inheritance modifier modifiers throw exception

This paper analyzes the difference between overloading and rewriting in Java in detail, and can be consulted by interested friends.

I. Overload (overloading):

(1) method overloading is a means of allowing classes to handle different types of data in a uniform manner. Multiple functions with the same name exist at the same time with a different number/type of arguments.
Overload overloading is a manifestation of polymorphism in a class.

(2) Java method overloading, in which you can create multiple methods in a class that have the same name but have different parameters and different definitions.
When you invoke a method, you decide which method to use by the number of different parameters and parameter types passed to them, which is polymorphism.

(3) When overloaded, the method name is 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.

The following are examples of overloads:

Package c04.answer;//This is the package name
//This is the first programming method of this program, create a dog class instance in the main method, and then invoke a different bark method using the This keyword in the constructor method of the dog class.
different overloaded method bark are differentiated according to their parameter types.
//Note: In addition to the constructor, the compiler prohibits invoking the constructor anywhere else.
package c04.answer;
public class Dog {
Dog ()
{
this.bark ()
}
The Void Bark ()//bark () method is an overloaded method
{
System.out.println (\ "No barking!\");
This.bark (\ "Female\", 3.4);
}
void Bark (String m,double L)//Note: The return value of the overloaded method is the same,
{
System.out.println (\ "A barking dog!\");
This.bark (5, \ "China\");
}
void bark (int a,string N)//cannot differentiate overloaded methods with the return value, and can only be distinguished by the "parameter type" and "class name"
{
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\");

Ii. rewriting (overriding)

(1) The polymorphism between the parent class and the subclass, redefining the function of the parent class. If you define a method in a subclass with the same name and parameters as its parent class, we say that the method is overridden (overriding). In, subclasses can inherit methods from the parent class without having to rewrite the same method.
But sometimes subclasses do not want to inherit the method of the parent class intact, but want to make some modifications, this requires the use of the method of rewriting.
Method overrides are also called method overrides.

(2) The method in the Jozo class has the same method name, return type, and parameter table as a method in the parent class, and the new method overwrites the original method.
You can use the Super keyword, which refers to the parent class of the current class, if you want to have methods in the parent class.

(3) The access modifier permission of the subclass function can not be less than the parent class;

Here is an example of a rewrite:

Concept: The mechanism by which the object method is invoked.

The Insider of dynamic binding:

1. The compiler examines the type and method names of object declarations to obtain all candidate methods. Try to comment out the test of the base class above, and then compile it.
2. Overload resolution: The compiler examines the parameter types of the method invocation, selecting the only one from the candidate method (there will be implicit type conversions).
If the compiler finds more than one or does not find it, the compiler will now complain. Try to comment out the previous example base class test (Byte B), which results in a 1 1 run.
3, if the method type is priavte static final, Java static compilation, the compiler will know exactly where the call
A method.
4. When a program is run and a method is invoked using dynamic bindings, the virtual machine must call the method version of the object's actual type.
In the example, the actual type pointed to by B is testoverriding, so b.test (0) invokes test of the subclass.
However, the subclass does not override test (byte b), so B.test ((byte) 0) invokes test (Byte B) of the parent class.
If you comment out the parent class (Byte B), the second implicit type is converted to int, and the final call is test (int i) of the subclass.

Third, Study summary:

Polymorphism is a feature of object-oriented programming that is independent of methods,
In short, the same method can be used to make different processing according to the input data, namely the method
overload--has a different argument list (static polymorphism)
and when the subclass inherits the same method from the parent class, the input data is the same, but to make a response different from the parent class, you override the parent class method.
That is , the method is overridden in a subclass-the same parameter, different implementations (dynamic polymorphism)

Three main features of OOP: inheritance, polymorphism, 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 at this point is 1 0, which is the result of dynamic binding at run time.

The main advantage of overriding 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 an inheritance relationship, overriding methods can only override methods that are not private to the parent class.
When the Father class speak () method in the previous example is private, the son class cannot rewrite the Father class speak () method, at which point the Son class speak () method is quite equivalent to a son () method defined in the Speak class.
Father class Speak () method when it is final, the son class cannot override the Father class speak () method at all, regardless of whether the method is public,protected and default decorated.
The compiler will complain when attempting to compile the code. Cases:

publicclassfather{
Finalpublicvoidspeak () {
System.out.println ("Father");
}
publicclasssonextendsfather{
Publicvoidspeak () {
System.out.println ("Son");
}
The compiler will make an error;

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

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

Rules for overriding methods:

1. The parameter list must be exactly the same as the overridden method, otherwise it cannot be called an override but an overload.
2. The returned type must always be the same as the return type of the overridden method, otherwise it cannot be called an override but an overload.
3. Access modifiers must be greater than the access modifier of the overridden method (Public>protected>default>private)
4, the overriding method must not throw a new check exception or a more extensive check-type exception than the overridden method declares. For example:
A method of the parent class declares a check exception ioexception, when overriding this method cannot throw exception, can throw only the IOException subclass exception, can throw the unchecked exception.

And the overloaded rules:

1, must have a different parameter list;
2, can have not scold the return type, as long as the parameter list is different can be;
3, can have different access modifiers;
4, can throw different anomalies;

The difference between overriding and overloading is:

Rewriting polymorphism works, and invoking overloaded methods can greatly reduce the amount of code input, and the same method name can have different functions or return values as long as it passes a different parameter to it.
With a good rewrite and overload, you can design a well-defined and concise class, and you can say that overrides and overloads are very important in writing code.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.