A constructor is a special method that is used toinitialize a newly created object and is called just after the memory is allocated for the object. It can be used to initialize the objects ,to required ,or default valuesat the time of object creation.It is not mandatory for the coder to write a constructor for the class.
It is a method with same name as class without any return type.
For Example:
class Foo
{
Foo()
{
//code in constructor
}
}
Example 2:
It is a method with same name as class without any return type.
For Example:
class Foo
{
Foo()
{
//code in constructor
}
}
Example 2:
class Demo{ int value1; int value2; Demo(){ value1 = 10; value2 = 20; System.out.println("Inside Constructor"); } public void display(){ System.out.println("Value1 === "+value1); System.out.println("Value2 === "+value2); } public static void main(String args[]){ Demo d1 = new Demo(); d1.display(); }}
No comments:
Post a Comment