G
G
gleendo2016-10-17 11:30:43
Java
gleendo, 2016-10-17 11:30:43

Why create a reference to an object?

Started learning Java. I still can’t understand why in the examples a reference to an object is created? Why can't you do without this link? What is she for?

abstract class Figure {
    double dim1;
    double dim2;

    Figure(double a, double b) {
        dim1 = a;
        dim2 = b;
    }

    abstract double area();
}

class Rectangle extends Figure {
    Rectangle(double a, double b) {
        super(a, b);
    }

    double area() {
        System.out.println("В области четырехугольника.");

        return dim1 * dim2;
    }
}

class Triangle extends Figure {
    Triangle(double a, double b) {
        super(a, b);
    }

    double area() {
        System.out.println("В области треугольника.");

        return dim1 * dim2 / 2;
    }
}

class Example {
    public static void main(String[] args) {
        Rectangle r = new Rectangle(9, 5);
        Triangle t = new Triangle(10, 8);
        
        Figure figref; // Вот эта ссылка
        
        figref = r;
        System.out.println("Площадь равна " + figref.area());
        
        figref = t;
        System.out.println("Площадь равна " + figref.area());
    }
}

Why do this? Why not just use this link and do this:
class Example {
    public static void main(String[] args) {
        Rectangle r = new Rectangle(9, 5);
        Triangle t = new Triangle(10, 8);

        System.out.println("Площадь равна " + r.area());
        System.out.println("Площадь равна " + t.area());
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2016-10-17
@zagayevskiy

Practically, for nothing. Just an illustrative example to explain polymorphism and inheritance.

M
Medin K, 2016-10-17
@medin84

For example, if there is a need to put objects in one list.
You can do it like this List < Object > , but in that case you have no way (without conditions and cast) to call the area method.
then you need to do List < Figure > and you can call area

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question