简体   繁体   中英

Overloading overridden method am I overloading parent or sub-class method

Overloading overridden method in subclass, am I overloading parent method or sub-classes method?

I understand generally what overloading and overriding is.

Overloading - same method different parameters and maybe return type in the same class.

Overriding - in subclass same method signature as in parent but different implementation.

class A {
    public void a() {
        System.out.println("A.a");
    }
}

class B extends A {
    public void a() {
        super.a();
        System.out.println("B.a");
    }

    public void a(int x) {

    }
}

Is method Ba(int x) overloading Aa or Ba?

Method Ba(int x) overloads Ba() , since method overloading resolution takes place at compile time, and depends on the compile time type of the variable for which you are calling the method.

On the other hand, the decision of which overridden method to execute takes place at runtime, and depends on the run-time type of the instance for which you are calling the method.

You can see that by trying the following code, which won't pass compilation, since class A has no method of the signature a(int x) :

A b = new B ();
b.a(4);

You override something that is inherited, so Ba() overrides Aa(). Overriding means to redefine.

Overloading is when your class have more than one definition of the same method name (each with different argument types). In B, the name a is overloaded. There is Ba() and Ba(int x).

Some of the definitions might be inherited. So if you remove Ba(), the class B would still have a method a() since it inherits it from A. And the method name a would still be overloaded in B.

ba(int x ) is overLoading a method of class Ba()

Rules of Overriding

Rule #1: Only inherited methods can be overridden.

Rule #2: Final and static methods cannot be overridden.

Rule #3: The overriding method must have the same argument list.

Rule #4: The overriding method must have the same return type (or subtype).

Rule #5: The overriding method must not have more restrictive access modifier.

It is overloading of subclass' method. That means Ba(int x) is an overloaded version of Ba() . Class A has not any method with the signature with public void a(int x) . So it's overloading of B's method public void a() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM