Java interface and exception experiment report

Posted by msk_1980 on Mon, 28 Oct 2019 03:06:22 +0100

Task 1: suppose the default length unit is meters, write a program to calculate the cost of coloring various shapes.
Requirement:

  1. Write the BorderColorable interface, which requires:
  • It has the method void paintBorder(), which needs to output "what shape's edge has been colored" in the implementation class.
  • Method boolean isBorderPainted() returns whether the edge of the shape has been shaded.
  1. Write the SolidColorable interface, which requires:
  • It has the method void paintShape(), which needs to output "what shape has been colored" in the implementation class.
  • Method boolean isShapePainted() returns whether the shape has been colored.
  1. Shape2D is an abstract class, which is the parent class of all shapes:
    Shape2D has the abstract methods double getPerimeter() and double getArea() to represent the perimeter and area of the acquired shape respectively.
  • Among them, circle, triangle and Rectangle are inherited from Shape2D class, while Square is inherited from Rectangle class.
  • Circle implements the BorderColorable interface, Triangle implements the SolidColorable interface, and Rectangle implements both the BorderColorable interface and the SolidColorable interface.
  1. CostCalculator class is used to calculate the cost of shading for edges and shapes.
  • Constructor CostCalculator(double borderCost, double solidCost), where borderCost represents the unit price needed to draw 1 meter edge.
    solidCost represents the unit price needed to draw 1 square meter of edge.
  • double calculate(Shape2D shape) is used to calculate the actual cost of shading the shape shape.
  • The cost calculation of shape shading only calculates the shaded part, and the total cost is the sum of the cost of edge shading and shape shading.
  1. Write a test class to test your program.

    First of all, let's analyze that to write interfaces and abstract classes, the basic statements should be clear (how to define abstract classes and remember that the methods in abstract classes must be implemented
/**
 * @Author:Chinese hawthorn tree
 * @Description:Shape2D Abstract class, the parent of all shapes
 * @Date: 2019/10/26
 * @Modified By:Chinese hawthorn tree
 */

public abstract class Shape2D {
    public abstract double getPerimeter();  //Circumference calculation
    public abstract double getArea();  //Calculated area
}

Then there are other subclasses in the abstract class. Because Rectangle and Square are special, po will give the code to see what happened when writing Square.

/**
 * @Author:Chinese hawthorn tree
 * @Description:rectangle
 * @Date: 2019/10/26
 * @Modified By:Chinese hawthorn tree
 */

public class Rectangle extends Shape2D implements BorderColorable,SolidColorable{
    private double length;
    private double width;
    private boolean isShapePainted = false;
    private boolean isSlidePainted = false;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    @Override
    public void paintBorder() {
        System.out.println("Edges of rectangle are shaded");
        isSlidePainted = true;
    }

    @Override
    public boolean isBorderPainted() {
        return isSlidePainted;
    }

    @Override
    public double getPerimeter() {
        return 2*(length + width);
    }

    @Override
    public double getArea() {
        return length*width;
    }

    @Override
    public void paintShape() {
        System.out.println("Rectangle shaded");
        isShapePainted = true;
    }

    @Override
    public boolean isShapePainted() {
        return isShapePainted;
    }
}

public class Square extends Rectangle{
    private double length;
    public Square(double length) { //Note constructor
        super(length, length);
        this.length = length;
    }
}

The last is the more important calculation class and test class. The main method used here is switch case to judge the shape and use shape.getClass().getSimpleName() to get the shape.

public class CostCalculator {
    private final double borderCost;
    private final double solidCost;

    public CostCalculator(double borderCost, double solidCost) {
        super();
        this.borderCost = borderCost;
        this.solidCost = solidCost;
    }
    public double calculate(Shape2D shape){
        switch (shape.getClass().getSimpleName()) {
            case "Rectangle":
            case "Square":
                return shape.getArea() * solidCost + shape.getPerimeter() * borderCost;
            case "Circle":
                return shape.getPerimeter() * borderCost;
            case "Triangle":
                return shape.getArea() * solidCost;
            default:
                return 0;
        }
    }
}

Finally, because the test class is relatively simple, the code is not spicy.~~
Task 2: write a program to cause the OutOfMemoryError of the JVM.
Requirement:

  1. The memory is allocated continuously in the program, which eventually causes the OutOfMemoryError error of the JVM.
  2. With try... catch catches this error and then looks at the total and free memory of the virtual machine at this time.
  3. In exception handling, an attempt is made to clear the allocated content space and recover the error.
  4. After error recovery, review the total and free memory again.
    Tips:
  • Try using Java's ArrayList class.
  • You can use the freeMemory() method of the Runtime class to view the free memory.
  • Use the totalMemory() method of the Runtime class to see the total memory. (the maxMemory() method can view the maximum available memory.)
  • When trying to recover this exception, you can empty the list object and use the System.gc() method to request the virtual machine for garbage collection.
  • Please understand the memory allocation principle of Java virtual machine through search engine.
    Let's review it first. What is OOM?
    Next is Several ways to clear list
    If you don't say much, go straight to the code:
public class OOMError {
    static List<UUID> list;

    public static void main(String[] args) {
        System.out.println("The total memory of the virtual machine before occupation is" + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "M");
        System.out.println("The free memory of the virtual machine before occupation is" + Runtime.getRuntime().freeMemory() / 1024 / 1024 + "M");
        try {
            list = new ArrayList<UUID>();
            while (true) {
                list.add(UUID.randomUUID());
            }
        }
         catch (OutOfMemoryError e){
             System.out.println("The total memory of the occupied virtual machine is" + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "M");
             System.out.println("The free memory of the occupied virtual machine is" + Runtime.getRuntime().freeMemory() / 1024 / 1024 + "M");
            }
        finally {
            System.out.println("Recovery error in progress");
            list.clear();
            Runtime.getRuntime().gc();
        }
    }
}

To be honest, I didn't use the ArrayList Instead, the integer.max'value is stored in the array, and the overflow effect is achieved by directly exploding the array. However, if there is a requirement for the goose problem, I have to change from ~ ~ to ArrayList, so I can use the same xio that is interested in Kangkang. The difference and implementation principle of ArrayList, LinkedList and Vector Ow (●  ̄ (エ) ~ ●)
be accomplished!! GAOCI

Topics: jvm Java