Priyanka
Priyanka

Reputation: 341

Java method inheritance problem when overloading the method

Here is my simple code to check Java inheritance & Method overloading. It gives compile error in my IDE. Could you please give an idea about this.? Error line commented in the code. If I comment that line program works fine and provide the given output.

class Bird {
    void sing() {
        System.out.println("I am Singing");
    }
}
class Peacock extends Bird {
    void sing() {
        System.out.println("I am Singing COO COO");
    }

    public void sing(String adverb) {
        System.out.println("I am Singing " + adverb);
    }
}
public class OverLoadingDemo {

    public static void main(String[] args) {
        Bird bird = new Peacock();
        bird.sing();//This return I am Singing COO COO
        bird.sing("Loudly");//ERROR The method sing() in the type Bird is not applicable for the arguments (String)
    }
}

Upvotes: 1

Views: 109

Answers (2)

WJS
WJS

Reputation: 40024

When you assign an object to the type of it's ancestors or interfaces, only the methods of the ancestor hierarchy or interface are visible to the object.

In your case a Peacock is a Bird so it knows about Peacock things and Bird things. But a Bird object (even if assigned from a Peacock object) only knows about Bird things that are common to all Birds. Hence, it won't know (and can't tell) that it is a Peacock.

This is the is-a relationship. A Peacock is-a Bird in all cases. But a Bird is not a Peacock in all cases.

Upvotes: 2

Andrew Merrill
Andrew Merrill

Reputation: 1742

The Java compiler sees that the type of the bird variable is Bird, and doesn't know that you are planning to store a reference to a Peacock in that variable. Since the Bird class does not have a method called sing that takes a String as an argument, it gives you an error.

If the Bird class had a sing method that took a String as an argument, then this code would compile. Even better, at runtime, it would use the version of the sing method (with a String argument) that was defined in the Peacock class since the variable bird would actually hold a Peacock object at that point.

Upvotes: 5

Related Questions