Answer to Question #214666 in Java | JSP | JSF for Fdfd

Question #214666
Create a class named Car. The Car class contains a static integer field named count. Create a constructor that adds 1 to the count and displays the count each time a Car is created. Create a destructor that subtracts 1 from the count and displays the count each time a Car goes out of scope. Write a main() function that declares an array of five Car objects. Output consists of five constructor messages and five destructor messages, each displaying the current count.
1
Expert's answer
2021-07-07T06:16:10-0400

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++.



Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS