#java #object #static #field #copy-constructor
#java #объект #статический #поле #конструктор копирования
Вопрос:
У меня вопрос, как я могу создать статические поля для подсчета количества объектов данного класса в памяти с помощью метода finalize (protected void finalize () throws Throwable)? Второй вопрос: хорошо ли я создаю конструкторы копирования в этом классе, например, если нет, то как мне это сделать?
public Rectangle(Rectangle point){
width = point.width
height = point.height
}
public class Point {
public int x = 0;
public int y = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point(int x) {
this.x = x;
}
}
class Rectangle {
public int width = 0;
public int height = 0;
Point origin;
// four constructors
public Rectangle() {
origin = new Point(0, 0);
}
public Rectangle(Point p) {
origin = p;
}
public Rectangle(int w, int h) {
this(new Point(0, 0), w, h);
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}
public int area() {
return width * height;
}
}
public class exa_1 {
public static void main(String[] args) {
Rectangle myRect = new Rectangle(5,10);
myRect.width = 40;
myRect.height = 50;
System.out.println("Area: " myRect.area());
}
}
Комментарии:
1. Не стесняйтесь принять и поддержать приведенный ниже ответ, если вы считаете, что он был вам полезен
Ответ №1:
Вот ответ для вашей справки:
1.) Для подсчета объекта в памяти
- Вы можете создать статическую переменную класса. Затем добавьте счетчик в конструктор и уменьшите счетчик в функции finalize.
2.) Для конструктора копирования нам нужна глубокая копия, поскольку Rectangle имеет изменяемый объект. Кроме того, вам также необходимо подсчитать объект в памяти.
Замечания: не рекомендуется использовать finalize(), поскольку он устарел в Java 9. Вот причины, по которым не следует его использовать:
a.) Нет гарантии выполнения в finalize() . Поскольку JVM вызывает finalize() , может возникнуть ситуация, когда JVM завершает работу слишком рано, а сборщик мусора не получает достаточно времени для создания и выполнения финализаторов.
б.) Завершение является сложным процессом и часто приводит к проблемам с производительностью, тупикам и зависаниям. Именно по этой причине Java также решила отказаться от него.
c.) метод finalize() не работает в цепочке, подобной конструкторам. Дочерний класс finalize() не вызывает функцию finalize() суперкласса.
d.) Любое исключение, вызванное методом finalize, приводит к остановке завершения этого объекта, но в противном случае игнорируется. Он даже не будет зарегистрирован в ваших файлах журналов. Если что-то пойдет не так, отладка становится практически невозможной.
class Point {
public static int count = 0;
public int x = 0;
public int y = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;
count ; //Add the object count
System.out.println("Point constructor. object count=" count);
}
public Point(int x) {
this(x,0);
}
@Override
protected void finalize() {
count--; //reduce the object count
System.out.println("Point finalize. object count=" count);
}
}
class Rectangle {
public static int count = 0;
public int width = 0;
public int height = 0;
Point origin;
public Rectangle() {
this(new Point(0, 0));
}
public Rectangle(Point p) {
this(p,0,0);
}
public Rectangle(int w, int h) {
this(new Point(0, 0), w, h);
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
count ; //Add the object count
System.out.println("Rectangle constructor. object count=" count);
}
//Copy constructor
public Rectangle(Rectangle rectangle) {
this(new Point(rectangle.getPoint().x, rectangle.getPoint().y), rectangle.width, rectangle.height);
}
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}
public int area() {
return width * height;
}
public Point getPoint() {
return origin;
}
@Override
protected void finalize() {
count--; //reduce the object count
System.out.println("Rectangle finalize. object count=" count);
}
}
public class exa_1 {
public static void main(String[] args) {
Rectangle myRect = new Rectangle(5,10);
myRect.width = 40;
myRect.height = 50;
System.out.println("Area: " myRect.area());
Rectangle myRect2 = new Rectangle(5,10);
myRect2.width = 60;
myRect2.height = 70;
System.out.println("Area: " myRect2.area());
Rectangle myRect3 = new Rectangle(myReact2);
System.out.println("Area: " myRect3.area());
myReact = null; //Set to null so that the object will be removed during gc
System.gc(); //to clear the memory
}
}