I am reviewing some importants rules in Java.
My questions are : Declaring a method do(double in) in a superclass and a method do(int in) in a subclass. Is the method do(int in) in the subclass is considered an overrided method of the superclass method do(double in), as an int can be put in a double, or is it considered as an overloaded method ?
I ask this question because this code :
Superclass subclass = new Subclass() subclass.do(10);
This code will call the superclass method.
I know that in the compile time, the compiler will put in the bytecode the compatible method present in the superclass and as it founds the do(double in) in the superclass which is a compatible one.
But why when the jvm will do the method implementation binding it doesn't take the method in the sub class, as the object is a Subclass ?
Does the jvm take the exact method signature found in the bytecode ?
I hope i am clear, sorry for my english.
I was expecting this code :
Superclass subclass = new Subclass() subclass.do(10);
calls the subclass methode do(int in).
In java, integer and double are two different types. The ONLY way to override a method in Java is to have the exact same signature:
class Parent() {
public void method(double a); //1
public void method(int a, double b); //2
}
class Child() extends Parent {
public void method(int a); //Not an override
public void method(String a); //Not an override
@Override
public void method(double a); //Overrides 1
public void method(double a, int b); //Not and override (order is wrong)
@Override
public void method(int a, double b); //Overrides 2
}
The method signature is a combination of the method name, the type of arguments, and order of those types (if multiple arguments).
For your question, I have tailored your code to match my example.
Parent child = new child();
child.method(10);
The compiler only knows that object child
is of type Parent
. Thus it treats it as a parent. It DOES NOT know that child
is actually of type Child
, a subtype of Parent
.
When you call child.method(10)
, the compiler sees Parent.method(10)
. Since 10 can be both an integer and a double, it calls the parent method.
I added method(String a)
to the child.
If you call child.method("10")
, again it sees Parent.method("10")
. The problem here is that Parent has no method(String a)
so the compiler will complain.
The only way to make this call the child method is to specify the parent as type Child.
Parent child = new child();
((Child) child).method(10);