Home> Java> javaTutorial> body text

The difference between overloading and rewriting in Java

巴扎黑
Release: 2017-06-23 16:37:34
Original
1254 people have browsed it

Attention, students learning Java! ! !
If you encounter any problems during the learning process or want to obtain learning resources, you are welcome to join the Java learning exchange group: 159610322 Let’s learn Java together!

First let’s talk about: Overloading


(1) Method overloading is to make the class uniform A means of handling different types of data. Multiple functions with the same name exist at the same time, with different number/type of parameters.

Overloading is a manifestation of polymorphism in a class.


(2) Java method overloading means that multiple methods can be created in a class. They have the same name but different parameters and different definitions.

When calling methods, the specific number and parameter types passed to them are used to determine which method to use. This is polymorphism.


(3) When overloading, 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 criterion for distinguishing overloaded functions.


The following is an example of overloading:
package c04.answer;//This is the package name
//This is the first programming method of this program, in the main method First create an instance of the Dog class, and then use the this keyword in the constructor of the Dog class to call different bark methods.

Different overloaded methods bark are distinguished according to their parameter types.

//Note: Except for the constructor, the compiler prohibits calling the constructor anywhere else.
package c04.answer;

public class Dog {
Dog()
this.bark();
void bark()// The bark() method is an overloaded method.

void bark(String m, double l)//Note: The return values of overloaded methods are the same,
System.out.println(\"a barking dog!\")
this.bark (5, \ "China \");
}
void Bark (int a, string n) // Types "and" class names "to distinguish from
{
System.out.println (\" a howling dog \ "); )
Dog dog = Dog dog = . );
//dog.bark(5, \"China\");




Then let’s talk about Overriding


(1) Polymorphism between the parent class and the subclass, redefining the functions of the parent class. If a method defined in a subclass has the same name and parameters as its parent class, we say the method is overriding. In Java, a subclass can inherit methods from a parent class without rewriting the same methods.

But sometimes the subclass does not want to inherit the method of the parent class unchanged, but wants to make certain modifications, which requires method rewriting.

Method overriding is also called method overwriting.

(2) If a method in the subclass has the same method name, return type, and parameter list as a method in the parent class, the new method will overwrite the original method.


If you need the original method in the parent class, you can use the super keyword, which refers to the parent class of the current class.


(3) The access modification rights of subclass functions cannot be less than those of the parent class;
The following is an example of rewriting:


Concept: the mechanism for calling object methods .

The inside story of dynamic binding:

1. The compiler checks the type and method name of the object declaration to obtain all candidate methods. Try to comment out the test of the Base class in the above example, and then the compilation will not pass.

2. Overload decision: The compiler checks the parameter type of the method call and selects the only one from the above candidate methods (there will be implicit type conversion during this process).

If the compiler finds more than one or none is found, the compiler will report an error. Try to comment out the test (byte b) of the Base class in the above example. The running result is 1 1.

3. If the method type is priavte static final and Java uses static compilation, the compiler will know exactly which
method to call.

4. When the program runs and uses dynamic binding to call a method, the virtual machine must call the method version that matches the actual type of the object.

In the example, the actual type pointed to by b is TestOverriding, so b.test(0) calls the test of the subclass.

However, the subclass does not override test(byte b), so b.test((byte)0) calls the test(byte b) of the parent class.

If you comment out the (byte b) of the parent class, the implicit type is converted to int through the second step, and the test(int i) of the subclass is finally called.

Learning summary:

Polymorphism is a feature of object-oriented programming and has nothing to do with methods.
Simply put, it means that the same method can be used based on Different input data requires different processing, that is, method overloading - with different parameter lists (static polymorphism)

And when the subclass inherits the same method from the parent class, The input data is the same, but when you want to make a response that is different from the parent class, you have to override the parent class method,

That is, rewrite the method in the subclass - the same parameters, different implementations (dynamic multiple Morphism)

The three major characteristics of OOP: inheritance, polymorphism, and encapsulation.

public class Base

{
void test(int i)
{
System.out.print(i);
}
void test(byte b ;
i++;
System.out.println(i); ## B.Test (0)
B.Test ((Byte) 0)
}
}


This is the output result of 1 0 at this time, this is the time of operation The result of dynamic binding.



The main advantage of overriding is the ability to define characteristics unique to a subclass:

public class Father{

public void speak(){

System.out.println(Father);

}


}

public class Son extends Father{

public void speak( ){

System.out.println("son");

}

}

This is also called polymorphism, and the overriding method only Can exist in an inheritance relationship. Overriding methods can only override non-private methods of the parent class.

When the Father class speak() method is private in the above example, the Son class cannot override the Father class speak() method. At this time, the Son class speak() method is equivalent to the one defined in the Son class. speak() method.

Once the Father class speak() method is final, regardless of whether the method is modified by public, protected or default, the Son class cannot override the Father class speak() method at all.

Try to compile the code , the compiler will report an error. Example:

public class Father{

final public void speak(){

System.out.println("Father");

}

}

public class Son extends Father{

public void speak(){

System.out.println("son");

}

} //The compiler will report an error;

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

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

Rules for overriding methods:

1. The parameter list must be completely the same as the overridden method, otherwise it cannot be called overwriting but overloading.

2. The return type must always be the same as the return type of the overridden method, otherwise it cannot be called overwriting but overloading.

3. The access modifier limit must be greater than the access modifier of the overridden method (public>protected>default>private)

4. The overridden method must not throw new Checked exceptions or checked exceptions that are broader than the overridden method declaration. For example:

A method of the parent class declares a checked exception IOException. When overriding this method, you cannot throw Exception. You can only throw exceptions of subclasses of IOException, and you can throw unchecked exceptions.

The rules for overloading:

1. Must have different parameter lists;

2. You can have non-blaming return types, as long as The parameter list is different;

3. You can have different access modifiers;

4. You can throw different exceptions;

The difference between rewriting and overloading is:

Rewriting polymorphism works, which can greatly reduce the amount of code input when calling overloaded methods. The same method name only needs to be passed to different parameters. You can have different functions or return values.

Using rewriting and overloading well can design a class with a clear and concise structure. It can be said that rewriting and overloading play an extraordinary role in the process of writing code.

Attention, students learning Java! ! !
If you encounter any problems during the learning process or want to obtain learning resources, you are welcome to join the Java learning exchange group: 159610322 Let’s learn Java together!

The above is the detailed content of The difference between overloading and rewriting in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!