Examveda
Examveda

What will be the output of the following program code?
class Rectangle{
      public int area(int length, int width){
            return  length*width;
      }
}
class Square extends Rectangle{
      public int area(long length, long width){
            return  (int) Math.pow(length, 2);
      }
}
public class Test{
      public static void main(String args[]){
            Square r = new Square();
            System.out.println(r.area(5 , 4));
      }
}

A. Will not compile.

B. Will compile and run printing out 20

C. Runtime error

D. Will compile and run printing out 25

Answer: Option B


This Question Belongs to Java Program >> Overriding And Overloading

Join The Discussion

Comments ( 7 )

  1. Abhishek Prasad
    Abhishek Prasad :
    10 months ago

    Child class reference can be used to call both parent and child class methods and in this program the arguments passed are int so be default at Run time parent object was been called and output is 20, If the arguments passed were (5l,4l) then the output would be 25. if anyone has a doubt you can compile and check the output.

    @Shrey Soni in this program dynamic polymorphism is not taking place and you can check the conditions for overriding a method properly, this is plain inheritance where parent class object is available to child class object and a parent method was called because of Argument type.

  2. Shrey Soni
    Shrey Soni :
    7 years ago

    The method call is bound to the object at run time, this is due to both present methods and program does not know which method call to bound to.
    This leads to the confusion until the objects are created. At creating the method call is bound to parent's method and invokes that method.
    This is called Dynamic polymorphism, or late binding, since dynamic polymorphism exploits the overriding.

  3. Shreyans Halani
    Shreyans Halani :
    7 years ago

    D is answer ...Because 5^2 =25

  4. Ashish Ranshinge
    Ashish Ranshinge :
    7 years ago

    The answer is 20 as we are passing int values. The parent class method accepts int values while the child class method accepts long values. Therefore the parent class method is called. If you pass (5L,4L) instead, the child class method is called and the answer comes to 25.

  5. PATEL NARLA
    PATEL NARLA :
    8 years ago

    25 IS THE ANS

  6. Sunny Bhan
    Sunny Bhan :
    8 years ago

    Math.pow(x,y)= x raise to the power y
    (5,2)= 5*5 = 25..
    20 seems in correct

  7. Manoj Samrat
    Manoj Samrat :
    8 years ago

    Square r equal to new square , so by the reference they call sub class . So answer is 25

Related Questions on Overriding and Overloading