Home Java javaTutorial Why does an exception occur when a subclass calls an overloaded method?

Why does an exception occur when a subclass calls an overloaded method?

Mar 08, 2024 pm 04:48 PM
Overload inherit transfer Compile Error

Why does an exception occur when a subclass calls an overloaded method?

Why does an exception occur when a subclass calls an overloaded method?

In object-oriented programming, overloading refers to defining multiple methods in the same class. These methods have the same name but different parameter lists to achieve different functional implementations. When a subclass inherits from a parent class, if there is an overload of a method with the same name in the subclass, exceptions may occur.

To explain more specifically why an exception is thrown when a subclass calls an overloaded method, let's look at the following code example:

class Parent {
    void display() {
        System.out.println("Parent class display method");
    }
    void display(int num) {
        System.out.println("Parent class display method with parameter");
    }
}

class Child extends Parent {
    void display() {
        System.out.println("Child class display method");
    }
}

public class Main {
    public static void main(String[] args) {
        Parent parent = new Child();
        parent.display();
        parent.display(10);
    }
}
Copy after login

In the above code, we define a parent class Parent and a subclass Child. There are two overloaded display methods in the parent class, which are the version without parameters and the one with an integer parameter. Version. The subclass Child inherits from the parent class Parent, and overrides the display method in the parent class.

In the Main class, we create a reference from the parent class to the object of the subclass. Then try calling the display method and the display(int num) method respectively. According to the principle of polymorphism, since the reference variable is of the parent class type and the actual object is of the subclass type, the method in the subclass Child should be called.

However, when you run the program, you will find that only the display method is called, and a compilation error will occur when calling the display(int num) method. This is because in the inheritance relationship, when a subclass overrides the method of the parent class, it does not overwrite the method of the parent class, but only adds a new overloaded method. Therefore, when an overloaded method is called through a parent class reference, the compiler will choose to call the method defined in the parent class rather than the overloaded method in the child class.

In order to solve this problem, we can declare the methods in the parent class as final, or overload all methods in the parent class in the child class to ensure that the child is called Method in a class without throwing an exception.

To sum up, exceptions will be thrown when subclasses call overloaded methods because in the inheritance relationship, subclasses overloading the methods of the parent class will not override the methods of the parent class, so you need to pay attention when using to avoid this situation.

The above is the detailed content of Why does an exception occur when a subclass calls an overloaded method?. 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

Video Face Swap

Video Face Swap

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

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)

Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? May 01, 2024 pm 10:27 PM

In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

What does val mean in java What does val mean in java Apr 25, 2024 pm 10:06 PM

The val keyword in Java is used to declare an immutable local variable, i.e. its value cannot be changed once assigned. Features are: Immutability: Once initialized, the val variable cannot be reassigned. Local scope: val variables are only visible within the block of code in which they are declared. Type inference: The Java compiler will infer the type of the val variable based on the assigned expression. Local variables only: val can only be used to declare local variables, not class fields or method parameters.

The difference between const and static in c++ The difference between const and static in c++ May 01, 2024 am 10:54 AM

The const modifier indicates a constant and the value cannot be modified; the static modifier indicates the lifetime and scope of the variable. Data members modified by const cannot be modified after initialization. Variables modified by static are initialized when the program starts and destroyed when the program ends. They will exist even if there is no active object and can be accessed across functions. Local variables modified by const must be initialized when declared, while local variables modified by static can be initialized later. Const-modified class member variables must be initialized in the constructor or initialization list, and static-modified class member variables can be initialized outside the class.

Detailed explanation of C++ function inheritance: How to debug errors in inheritance? Detailed explanation of C++ function inheritance: How to debug errors in inheritance? May 02, 2024 am 09:54 AM

Inheritance error debugging tips: Ensure correct inheritance relationships. Use the debugger to step through the code and examine variable values. Make sure to use the virtual modifier correctly. Examine the inheritance diamond problem caused by hidden inheritance. Check for unimplemented pure virtual functions in abstract classes.

What does = mean in java What does = mean in java Apr 26, 2024 pm 11:30 PM

The "=" operator in the Java programming language is used to assign a value to a variable, storing the value on the right side of the expression in the variable on the left. Usage: variable = expression, where variable is the name of the variable that receives the assignment, and expression is the code segment that calculates or returns the value.

Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? May 02, 2024 am 08:18 AM

Detailed explanation of C++ function inheritance: Master the relationship between "is-a" and "has-a" What is function inheritance? Function inheritance is a technique in C++ that associates methods defined in a derived class with methods defined in a base class. It allows derived classes to access and override methods of the base class, thereby extending the functionality of the base class. "is-a" and "has-a" relationships In function inheritance, the "is-a" relationship means that the derived class is a subtype of the base class, that is, the derived class "inherits" the characteristics and behavior of the base class. The "has-a" relationship means that the derived class contains a reference or pointer to the base class object, that is, the derived class "owns" the base class object. SyntaxThe following is the syntax for how to implement function inheritance: classDerivedClass:pu

What does eclipse mean when it says that the main class cannot be loaded? What does eclipse mean when it says that the main class cannot be loaded? May 05, 2024 pm 07:09 PM

Solution to the "Error: Could not find or load main class" error in Eclipse: Check whether the main class exists and the path is correct. Verify that the main class is in the correct package and that public access allows Eclipse access. Check the classpath configuration to ensure that Eclipse can find the class file for the main class. Compile and fix the error that caused the main class to fail to load. Check the stack trace to identify the source of the problem. Compile from the command line using the javac command and check the error messages. Restart Eclipse to resolve potential issues.

How to bring up the eclipse navigation bar How to bring up the eclipse navigation bar May 05, 2024 pm 07:12 PM

The Eclipse navigation bar can be displayed via the menu: Window > Show View > Navigation Shortcut key: Ctrl + 3 (Windows) or Cmd + 3 (Mac) Right-click the workspace > Show View > Navigation The navigation bar contains the following functions: Project Resource Browser: Shows folders and files Package Resource Browser: Shows Java package structure Problem View: Shows compilation errors and warnings Task View: Shows tasks Search field: Searches for code and files Bookmark View: Marks lines of code for quick access

See all articles