Home Java javaTutorial The difference between overloading and rewriting in Java

The difference between overloading and rewriting in Java

Jun 23, 2017 pm 04:37 PM
java the difference Overload

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

deepseek What is the difference between r1 and v3 version deepseek What is the difference between r1 and v3 version Feb 19, 2025 pm 03:24 PM

DeepSeek: In-depth comparison between R1 and V3 versions helps you choose the best AI assistant! DeepSeek already has tens of millions of users, and its AI dialogue function has been well received. But are you confused when facing the R1 and V3 versions? This article will explain the differences between the two in detail to help you choose the most suitable version. The core difference between DeepSeekR1 and V3 version: Features The design goal of the V3 version focuses on complex problem reasoning, deep logic analysis, multi-functional large language model, focusing on scalability and efficiency architecture and parameter reinforcement learning optimization architecture, parameter scale 1.5 billion to 70 billion MoE hybrid Expert architecture, total parameters are as high as 671 billion, each token is activated by 37 billion

Summary of FAQs for DeepSeek usage Summary of FAQs for DeepSeek usage Feb 19, 2025 pm 03:45 PM

DeepSeekAI Tool User Guide and FAQ DeepSeek is a powerful AI intelligent tool. This article will answer some common usage questions to help you get started quickly. FAQ: The difference between different access methods: There is no difference in function between web version, App version and API calls, and App is just a wrapper for web version. The local deployment uses a distillation model, which is slightly inferior to the full version of DeepSeek-R1, but the 32-bit model theoretically has 90% full version capability. What is a tavern? SillyTavern is a front-end interface that requires calling the AI ​​model through API or Ollama. What is breaking limit

Does Bitcoin have stocks? Does Bitcoin have equity? Does Bitcoin have stocks? Does Bitcoin have equity? Mar 03, 2025 pm 06:42 PM

The cryptocurrency market is booming, and Bitcoin, as a leader, has attracted the attention of many investors. Many people are curious: Do Bitcoin have stocks? The answer is no. Bitcoin itself is not a stock, but investors can indirectly invest in Bitcoin-related assets through various channels, which will be explained in detail in this article. Alternatives to Bitcoin Investment: Instead of investing directly in Bitcoin, investors can participate in the Bitcoin market by: Bitcoin ETF: This is a fund traded on the stock trading market, whose asset portfolio contains Bitcoin or Bitcoin futures contracts. This is a relatively convenient option for investors who are accustomed to stock investments, without having to hold Bitcoin directly. Bitcoin Mining Company Stocks: These companies' business is Bitcoin mining and holding Bitcoin

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

What is the difference between pre-market and after-market trading? Detailed explanation of the differences between pre-market and after-market trading What is the difference between pre-market and after-market trading? Detailed explanation of the differences between pre-market and after-market trading Mar 03, 2025 pm 11:54 PM

In traditional financial markets, pre-market and after-market trading refers to trading activities outside the regular trading period. Although the cryptocurrency market is trading around the clock, trading platforms like Bitget also offer similar features, especially some comprehensive platforms that trade stocks and cryptocurrencies at the same time. This article will clarify the differences in pre-market and after-market trading and explore its impact on currency price. Four major differences between pre-market and after-market trading: The main differences between pre-market and after-market trading and regular trading periods are in four aspects: trading time, liquidity, price fluctuations and trading volume: Trading time: Pre-market trading occurs before the official trading starts, and after-market trading is carried out after the regular trading ends. Liquidity: The liquidity of pre- and after-hours trading is low, there are few traders, and the bid and offer price difference is large; while the liquidity is high during the regular trading period, the price is

Why is Bittensor said to be the 'bitcoin' in the AI ​​track? Why is Bittensor said to be the 'bitcoin' in the AI ​​track? Mar 04, 2025 pm 04:06 PM

Original title: Bittensor=AIBitcoin? Original author: S4mmyEth, Decentralized AI Research Original translation: zhouzhou, BlockBeats Editor's note: This article discusses Bittensor, a decentralized AI platform, hoping to break the monopoly of centralized AI companies through blockchain technology and promote an open and collaborative AI ecosystem. Bittensor adopts a subnet model that allows the emergence of different AI solutions and inspires innovation through TAO tokens. Although the AI ​​market is mature, Bittensor faces competitive risks and may be subject to other open source

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Is there any difference between South Korean Bitcoin and domestic Bitcoin? Is there any difference between South Korean Bitcoin and domestic Bitcoin? Mar 05, 2025 pm 06:51 PM

The Bitcoin investment boom continues to heat up. As the world's first decentralized digital asset, Bitcoin has attracted much attention on its decentralization and global liquidity. Although China was once the largest market for Bitcoin, policy impacts have led to transaction restrictions. Today, South Korea has become one of the major Bitcoin markets in the world, causing investors to question the differences between it and its domestic Bitcoin. This article will conduct in-depth analysis of the differences between the Bitcoin markets of the two countries. Analysis of the differences between South Korea and China Bitcoin markets. The main differences between South Korea and China’s Bitcoin markets are reflected in prices, market supply and demand, exchange rates, regulatory supervision, market liquidity and trading platforms. Price difference: South Korea’s Bitcoin price is usually higher than China, and this phenomenon is called “Kimchi Premium.” For example, in late October 2024, the price of Bitcoin in South Korea was once

See all articles