Monday, September 19, 2011

SOME IMPORTANT LINES ABOUT JAVA CONSTRUCTOR



1) Constructors can use any access modifier, including private. (A private
constructor means only code within the class itself can instantiate an object
of that type, so if the private constructor class wants to allow an instance
of the class to be used, the class must provide a static method

2) It's legal (but stupid) to have a method with the same name as the class,
but that doesn't make it a constructor. If you see a return type, it's a method
rather than a constructor.

3) If you don't type a constructor into your class code, a default constructor will
be automatically generated by the compiler.

4) The default constructor is ALWAYS a no-arg constructor.

5) If you want a no-arg constructor and you've typed any other constructor(s)
into your class code, the compiler won't provide the no-arg constructor (or
any other constructor) for you. In other words, if you've typed in a constructor
with arguments, you won't have a no-arg constructor unless you type it in
yourself !

6) Every constructor has, as its first statement, either a call to an overloaded
constructor (this()) or a call to the superclass constructor (super()), although
remember that this call can be inserted by the compiler.

7) Interfaces do not have constructors. Interfaces are not part of an object's
inheritance tree.

8) The only way a constructor can be invoked is from within another constructor.
In other words, you can't write code that actually calls a constructor as
follows:
class Basic{

Basic()
{ } // constructor

void doStuff() {

Basic(); //constructor calling :illegal!

}
}

No comments:

Post a Comment