Please clarify my doubt on overriding, When I am calling a method which is not overrided, the method that is being called is form parent class, please give brief explanation on this, The example is like this
public class A {
public void test(int x){
System.out.println("Haiiiiiii");
}
}
public class B extends A{
public void test(Integer x){
System.out.println("hiii Im b's method");
}
}
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
B a=new B();
a.test(2);
}
}
I'm calling b's method but in B class the method takes wrapper class as parameter.
There are 2 methods. One accept int
and other accept Integer
type. So when you call test()
method first it try to find a suitable method without doing any autoboxing
. In that case it can find the parent class test()
method which accept an int. Therefore java will execute that.
If in case it wouldn't exist then it will try to autobox
your parameter and check if there a suitable method. In that case your child class method will get execute.
Edited Java will always pick the most specific method for a type. Casting/autoboxing/unboxing only when it has to.
If you wanna call child class method you can try
a.test(new Integer(2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With