1) Both Constructor and Destructor are member functions of the class.
2) Both are made by the language defaultly and can be override by the programmer.
3) The constructor is being called when a new object of the class is created
It can be used to initiate members to call functions and what ever is needed when an instance of the class is being made
Simple Meaning:
Constructor:
1) It is like a member function.
2) Consturctor name must be class name
3) It doesnot have any return type.
Ex:
class another{
int x,y;
another(int a, int b) {
x = a;
y = b;
}
another(){} }
*Every class has at least one it's own constructor
*Constructor creates a instance for the class.
* Like Methods ,Constructor overloading also available.
Destructor:
The aim of destructor in any OOPs language is:
- Free up the memory (c++ suffer from memory allocation / deallocation)
- Clean up any other resources (like closing of open file stream)
Java take cares of all and hence there is no destructor in JAVA. (With the help of Garbage collection). but still if you want to perform some additional tasks, then you can use the finalize() method of java.
But, we can’t rely on finalize() as it depends on GC. Sometimes, GC may never be invoked during the lifetime of the program.
A good idea is to implement a method, say cleanUp() which does, any special processing required, ofcourse, other than freeing up memory.
The programmer should call this method(finalize()) at the approppriate place in the program. That is the only way to make sure your program works correctly.
class Thing { |
| public static int number_of_things = 0; |
| public String what; |
|
| public Thing (String what) { |
| this.what = what; |
| number_of_things++; |
| } |
|
| protected void finalize () { ----> destructor |
| number_of_things--; |
| } |
| } |
|
| public class TestDestructor | { |
| public static void main(String[] args) |
| { |
| Thing obj = new Thing("Test App"); |
| } |
| } |

0 comments:
Post a Comment