如何声明在删除类的实例时将要完成的事情?

问题描述 投票:0回答:1
public class Circle {

    private static int numberOfCircles = 0;
    private static int ID;
    public Point center = new Point();
    public int radius;

    public Circle(@NotNull Point getPoint, int r){
        ID = ++numberOfCircles;
        this.center.x = getPoint.x;
        this.center.y = getPoint.y;
        this.radius = r;

        public static int getNumberOfCircles () { return numberOfCircles; }

        public int getID() { return ID; }

我想在删除Circle对象时将numberOfCircles变量减1。这可能吗?如果是这样,请有人可以帮助我吗?预先感谢。

java oop instance instance-variables
1个回答
0
投票

您可以在Circle类中添加delete()方法

    public void delete() {
        this.numberOfCircles--;
    }

然后您可以像这样调用它:

    // Create Circle
    Circle c = new Circle(point, 2);
    // Do something
    ...
    // Delete circle
    c.delete();
    c = null;
© www.soinside.com 2019 - 2024. All rights reserved.