The difference between overloading and rewriting in Java
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.
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)
{
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

The key differences between CentOS and Ubuntu are: origin (CentOS originates from Red Hat, for enterprises; Ubuntu originates from Debian, for individuals), package management (CentOS uses yum, focusing on stability; Ubuntu uses apt, for high update frequency), support cycle (CentOS provides 10 years of support, Ubuntu provides 5 years of LTS support), community support (CentOS focuses on stability, Ubuntu provides a wide range of tutorials and documents), uses (CentOS is biased towards servers, Ubuntu is suitable for servers and desktops), other differences include installation simplicity (CentOS is thin)

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.
