Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects Meet Objects Constructors

toni chen
toni chen
3,865 Points

constructor vs destructor

What is the difference between constructor and destructor and how its work ? i demand you to provide with some example ! lol

2 Answers

Dino Šporer
Dino Šporer
5,430 Points

When you create class, constructor creates and gives value to your private variable so you don't have to do it later. So if you have mAge and mName, and pass values 5 and "Nick" in constructor, mAge will be 5 and mName will be Nick. And desctructor clears and free some space in memory after you stop using those class. In c++ for example, you had to call a destrcutor, in Java, you don't have to.

toni chen
toni chen
3,865 Points

String statement = "Destructor clears and free some space in memory after you stop using those class"; what the "stop using" words refering to, its mean "when you stop running or compile those class" or when your program is done compiling ?? at the end it will automatically destroy those memory ??

Dino Šporer
Dino Šporer
5,430 Points

Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor.

There is an inherited method called finalize, but this is called entirely at the discretion of the garbage collector. So for classes that need to explicitly tidy up, the convention is to define a close method and use finalize only for sanity checking (i.e. if close has not been called do it now and log an error).

You dont have destructor in java. You actually just have garbage collector , and you don't know exactly time of deleting your class.