Circle class:
UPD: The code has been redone, at the request of the author, now the variables of the class Figure cannot be changed, are set once during creation
It is better not to put any calculations in the constructor, since various exceptions can be thrown in there, and it is better not to put methods there, since calling some methods in which, for example, some variables can not be predefined or initialized. However, the method can be called if you are 100% aware that there will not be the problems described above. Such a method is desirable should only define the object, and manipulate only the variables it receives, otherwise, as he said earlier, there may be a problem. In mathArea () and mathPerimeter (), you will need to create exception handling. There is a so-called public static method to which the radius value is passed, and if it does not comply with the conditions, an object is not created, without this method in the constructor, in the setRadius (..) method; if a negative value is passed, the object would be CREATED, and would return default double area and parameter values, which is not acceptable. There is a NullPointerException exception when trying to create and modify an object, as shown in qew.java, and it is necessary for each shape to set individual exception handling in methods, during creation, etc., where this is actually possible. There are also other advantages of such an architecture, if you are interested in which, write down
public class Circle extends Figure { private double radius; public static Circle createCircle(double radius) { if(radius <= 0) {System.out.println("WHY ? Stop it...");return null;} else return new Circle(radius); } public Circle(double radius) { setRadius(radius); } private double mathArea() { return Math.pow(radius,2)*Math.PI; } private double mathPerimeter() { return 2*radius*Math.PI; } private void setRadius(double radius){ this.radius = radius; super.setPerimeter(mathPerimeter()); super.setArea(mathArea()); } }
Class qew.java, I have with the main method: Test, an attempt to create an object with a negative radius.
public class qew { public static void main(String[] args) { Circle c = Circle.createCircle(4); System.out.println(c.getArea()); System.out.println(c.getPerimeter()); } }
Class Figure: The class is abstract, for why we need its instances, it must provide MANDATORY variables that 100% will be used for its descendants, otherwise, you need to define them in classes - descendants. This also applies to methods.
abstract public class Figure { private double area; private double perimeter; public double getArea() { return area; } public void setArea(double area){ this.area = area; }; public double getPerimeter() { return perimeter; } public void setPerimeter(double perimeter){ this.perimeter = perimeter; }; }