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)
}
}
sing(String)method, you need to call it on a type of variable which has that method.Birddoes not. Even though at runtime your variable holds a reference to an object which does have that method, it's the type at compile-time that counts when resolving the method.