Answer the question
In order to leave comments, you need to log in
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());
}
}
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
Practically, for nothing. Just an illustrative example to explain polymorphism and inheritance.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question