0

Below is the code I'm trying to run. If I remove the parameters from func() methods than the obj.func() call B class method but if I introduce the parameters it calls A class method.

public class A {
     void func(A obj) {
        System.out.println("in A");
      }
}

public class B extends A{
    void func(B obj) {
      System.out.println("in B");
    }
 
public static void main(String[] args) {
    A obj = new B();
    obj.func(null);// calls A class method, but why???
}}
Nitin
  • 1

1 Answers1

1

I suppose that you are trying to override method func of class A in class B. Anyway, your code is overloading the method, because the type of the parameters of A.func and of B.func are different. The former receives an object obj of type A, while the second receives an object obj of type B.

public class A {
    void func(A obj) {
        System.out.println("in A");
    }
}

public class B extends A{
    void func(B obj) { // your solution, which creates a DIFFERENT method using overloading
        System.out.println("OVERLOAD in B");
    }
    void func(A obj) { // proper override of *A.func(A obj)*
        System.out.println("OVERRIDE in B");
    }
} // <- pay attention, you forgot this bracket
 
public static void main(String[] args) {
    A obj = new B();
    obj.func(null);// now it calls the right method
}}

If you remove the parameter of func, the two functions are identical, hence you have a proper override. That is why removing the argument the code worked properly.

I hope I was able to help you, anyway you can find more information here:

Have a good day!