Reputation: 2657
Here is the code I wrote:
https://pastebin.com/raw/0iBrGJR4
Most relevant parts:
A a = new A();
B b = new B();
System.out.println(((A) b).a());
System.out.println(((A) b).b(3));
static class A {
Object a() {
System.out.println("A.a()");
}
Object b(Number x) {
System.out.println("A.b()");
}
}
static class B extends A {
String a() {
System.out.println("B.a()");
return "hello";
}
String b(Integer x) {
System.out.println("B.b()");
return "hola" + x;
}
}
When I run this, the first print displays
B.a()
hello
which is what I expected, since even though we cast to A, the call goes through to the object's actual type which is B.
But the second print, the ((A) b).b(3) call, prints
A.b()
3
(i.e. it calls the method in A). Force casting 3 to Integer doesn't do anything either. Can someone explain this behavior to me? I don't understand what the reason is. I would've expected ((A) b).b(3) to print B.() \n hola3
rather than use the parent class method.
Upvotes: 2
Views: 89
Reputation: 2616
In Java, what makes a method override another method in a parent class is if it has the same name but different number and/or types of arguments.
In your case class A
has a method b(Number x)
and class B
that extends A
has a method b(Integer x)
==> B.b()
doesn't override A.b()
==> when executing ((A) b).b(b)
, A.b(3)
is executed.
On the contrary, B.a()
does override A.a()
==> when executing ((A) b).a()
, B.a()
is executed.
The return value of the methods doesn't matter when overriding, only name and arguments.
Upvotes: 2