Passing Parameter as Wrapper Class and Overriding

Please clarify my doubts about overriding. When I call a method that is not overridden, the method that is called is the parent class of the form, please give a short explanation on this. An example is 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 method");
        }
   }

   public class Main {
        /**
         * @param args
         */
        public static void main(String[] args) {
            B a=new B();
            a.test(2);
        }
   }

      

I call method b, but in class B, the method takes a wrapper class as a parameter.

+3


source to share


3 answers


There are 2 methods. One accepts the int

other accept type as well Integer

. So when you call a method test()

first, it tries to find a suitable method without any autoboxing

. In this case, it can find a method of the parent class test()

that accepts an int. So java will do it.

If in case it doesn't exist, it will try autobox

to specify its parameter and check if there is a suitable method. In this case, your child class method will get executed.

The edited Java will always choose the most specific method for the type. Casting / autoboxing / unboxing only when needed.



If you want to call a method of the child class you can try

a.test(new Integer(2));

      

+3


source


In this case, overriding

it will not happen. because overloading

when you call it the accept input method is called as int

.



0


source


Compilation allows you to automatically open and unpack between primitives and wrappers, but it doesn't subclass one of the other. int

and Integer

are two different types, so both of them, when used in a method, act as two different methods (as in your case)

See link below for a clearer explanation int does not override Integer in Java

0


source