Hi
can any one tell me what is functionality of constructor....................?
Printable View
Hi
can any one tell me what is functionality of constructor....................?
It is code that is executed when you create an object.
As the first responder asked you, have you tried google before posting it here? I think most of us get tempted to post questions even though they might be within reach (answers). Nevertheless, I will answer that for you: A constructor is like a method but it MUST have the same name as the class and it is used to initialize the members of that class. It can have parameters or be default - without parameters. Consider:
I hope this will help you.
You aren't helping the OP much (regardless of how simple the question is) by posting unformatted code. Nobody wants to read it. Put your code in code blocks please.
In response:
Like qurtan stated, a constructor is code that is run when the object is initialized. You can use it to set variables the Object needs at the start of its life or make the caller provide the object with vital information it needs to function.
Code java:[CODE] public class MyObject { //Note the public keyword. Constructor access can be modified just like a method. Public, protected, private and default are all supported. //Also note that a constructor MUST have the same name as the class and compilation unit. Otherwise it is invalid. public MyObject() { //Initialization code here } //Note the difference between a constructor and a method. Methods have return types (like void -aka- return nothing). public void sayHello() { System.out.println("Hello world"); } } A constructor with parameters: public class Website { URL url; public Website(URL url) { this.url = url; } } [/CODE]
Constructors are also inherited by superclasses, and you can call upon the superclass constructor at the beginning of the subclass constructor using the super keyword.
Thanx fot this great info. I was needy about this.. Thanks you have solved my problems
Just to add some rules which will apply to constructors other then these constructor is just a normal method.
Constructor Rules
A constructor can't have a return type.
Constructor must have the same name as class name.
Constructors can't be marked static
Constructor can't be marked Final or abstract
Note: Constructor can't be overridden.
Quoted from URL