Java doesn't have destructors in the direct sense. The only simple way is to inherit method finalize() that is called by GC when the resourse comes out of scope. But it's not guaranteed to be called on time, and even be called.
More details: https://stackoverflow.com/questions/171952/is-there-a-destructor-for-java
The other way is to
Anyway, here is the code:
import java.io.*;
class Car
{
static int count = 0;
Car()
{
count++;
System.out.println("Car created, count = " + count);
}
protected void finalize()
{
count--;
System.out.println("Car destroyed, count = " + count);
}
public static void main (String[] args) throws java.lang.Exception
{
Car[] cars = new Car[5];
for (int i = 0; i < 5; i++)
cars[i] = new Car();
}
}
Another way is to inherit from Autocloseable interface and use the construction try-with-resources. BUT, as you have to declare a closeable variable inside try() expression, it will not be possible to use an array.
import java.io.*;
class Car implements AutoCloseable
{
static int count = 0;
Car()
{
count++;
System.out.println("Car created, count = " + count);
}
public void close()
{
count--;
System.out.println("Car destroyed, count = " + count);
}
public static void main (String[] args) throws java.lang.Exception
{
try(Car car1 = new Car();
Car car2 = new Car();
Car car3 = new Car();
Car car4 = new Car();
Car car5 = new Car())
{}
}
}
I think that the task wants to understand, that in Java you are not allowed to destroy objects on your will, like in C++.
Comments
Leave a comment