Jerry9912
Jerry9912

Reputation: 5

Method overloading and inheritance in java

I have the following program but it wont compile:

public class A {

    public void method() {
        System.out.println ("bla");
    }
}

class AX extends A {

    public void method(int a) {
        System.out.println ("Blabla");
    }

    public static void main(String[] args) {
        A a2 = new AX();
        a2.method(5);
    }
}

Why doesn't a2.method(5) use the subclasses method? Isn't this method overloading?

Upvotes: 0

Views: 1122

Answers (3)

prsmax
prsmax

Reputation: 223

In Java visibility determined by Object type, not by Reference type.

In your case:

A a2 = new AX();

Object type A, so compiler can't find method(int a);

Upvotes: 0

Michal Krasny
Michal Krasny

Reputation: 5926

Maybe you confuse terms overloading and overriding.

Overloading is adding a different method with same name as existing one, that differs in input parameters and return type. It has nothing to do with inheritance. From the inheritance point of view overloading is just adding a new method. Your class A has no idea, what it's successors new methods are.

Overriding is replacing a method with a different implementation. A knows that there exists a method, therefore you can change it in it's successor AX.

You have two possibilities. Either define public void method(int a) in A:

public class A {

    public void method() {
        System.out.println ("bla");
    }

    public void method(int a) {
        System.out.println ("Blabla from A");
    }
}

or use AX

AX a2 = new AX();
a2.method(5);

because the only class, that knows about the public void method(int a) is AX.

Upvotes: 1

Philipp
Philipp

Reputation: 333

Only methods of class A are visible to the compiler. This is because your Object a2 is of type A according to A a2 = new AX();. If you change this line to AX a2 = new AX(); it will work.

Upvotes: 1

Related Questions