Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameter as Wrapper class and overriding

Tags:

java

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.

like image 492
user3748274 Avatar asked Sep 06 '25 03:09

user3748274


1 Answers

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));
like image 72
Thusitha Thilina Dayaratne Avatar answered Sep 07 '25 23:09

Thusitha Thilina Dayaratne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!