Can we access the members of sub class using the refrenced variable of super class which holds the subclass object?

54 Views Asked by At

If not,then for the below program, how is the multiplication(method) of subclass is accessed Since I used the refrence variable of superclass Calculation which holds object of subclass My_Calculation. Output of below program is: The sum of the given numbers:30 The difference between the given numbers:10 The product of the given numbers in sub class is:200

class Calculation {
int z;

public void addition(int x, int y) {
   z = x + y;
   System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y) {
   z = x - y;
   System.out.println("The difference between the given numbers:"+z);
}
public void multiplication(int x, int y) {
   z = x * y;
   System.out.println("The product of the given numbers in super class is :"+z);
}
}

public class My_Calculation extends Calculation {
public void multiplication(int x, int y) {
   z = x * y;
   System.out.println("The product of the given numbers in sub class is:"+z);
}

public static void main(String args[]) {
   int a = 20, b = 10;
   Calculation demo = new My_Calculation();
   demo.addition(a, b);
   demo.Subtraction(a, b);
   demo.multiplication(a, b);
}
}

I was expecting error since we can only access the member of super class using the refrence of super class.

1

There are 1 best solutions below

0
luckyqiao On

A subclass has same method with its super class in java is called method overriding. When an overridden method is called through a superclass reference, Java determines which version(superclass/subclasses) of that method is to be executed. Which method is called is determined by the type of the object being referred to, but not the type of the reference variable. This is Runtime Polymorphism in Java.

In your code, the multiplication method of subclass is called, because the object's real type is My_Calculation