Search code examples
javaobjectabstract-classreference-type

When to use a specific or abstract reference type?


I'm still confused on what a reference type does/when to use which reference. Lets say Geometric Object is an abstract class and the circle class is a subclass that extends GeometricObject. What would the difference between these two lines be? When would one be preferred over the other?

GeometricObject circle1 = new Circle();
Circle circle2 = new Circle();

Solution

  • Here is a example to better understand :

    GeometricObject abstract class :-

    public abstract class GeometricObject {
        int answer;
        public void addition(int x, int y){
            answer=x+y;
              System.out.println("The sum is :"+answer);
           }
        public void substraction(int x,int y){
            answer=x-y;
              System.out.println("The difference is :"+answer);
           }
    }
    

    Circle subclass:

    public class Circle extends GeometricObject {
        int answer;
        public void multiplication(int x, int y) {
            answer = x * y;
            System.out.println("The product is :" + answer);
        }
    
        public static void main(String arg[]) {
            int a = 11, b = 8;
            GeometricObject circle1 = new Circle();
            circle1.addition(a, b);
            circle1.substraction(a, b);
            // circle1.multiplication(a, b); cannnot call the method. Its undifined for the GeometricObject
    
            Circle circle2 = new Circle();
            circle2.addition(a, b);
            circle2.substraction(a, b);
            circle2.multiplication(a, b);
        }
    }
    

    enter image description here

    The Superclass reference variable can hold the subclass object, but using that variable you can access only the members of the superclass, so to access the members of both classes it is recommended to always create reference variable to the subclass.

    Note: A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

    (Sorry for not using exact methods according to the class definition :))