0
class Student 
{
     void cal(int ...x)
     {
         System.out.println("Parent");
     }

}


class HelloWorld extends Student 
{

    void cal(int x)
  {
    System.out.println("Child");
  }

    public static void main(String... args)
  {
        Student ref = new HelloWorld();
        ref.cal(10);
  }

}

OUTPUT: Parent

While compiling, the compiler checks whether cal(int) is present in Student class or not. Once confirmed, when running the JVM tries to match the cal(int) based on the runtime object i.e. HelloWorld in this case. So it should match cal(int) with cal(int x) and the output should be "Child".

So then why is the output "Parent"

Above logic derived from: https://stackoverflow.com/a/70903492/13146358

  • 1
    "Once confirmed" <--- but `cal(int)` does not exist in `Student`... There is only the varargs method in `Student`. – Sweeper Feb 01 '22 at 13:57
  • @Sweeper The var-args methods can accept 10 as a value. – Karan Guleria Feb 01 '22 at 13:59
  • What type of datatype is variable `ref`? – Aditya Arora Feb 01 '22 at 14:01
  • 2
    But the `cal(int...)` method is not `cal(int)`. So, the compiler selects the method `cal(int...)` and this is the method which will be invoked at runtime. Don’t make your life so hard. Just add `@Override` to `void cal(int x)` and the compiler will immediately generate an error telling you that this method *does not override* any method. – Holger Feb 01 '22 at 14:04
  • @Holger I've got it. Thank you for your help. – Karan Guleria Feb 01 '22 at 14:13

0 Answers0