A constructor is a special purpose java class method used for initializing a class object. While creating a
constructor keep the following points in mind.
1. The name of the constructor is same as the class name.
2. There is no return type for a constructor.
3. A constructor invokes automatically when we create an object of that class.
Suppose we have the following class and we need a constructor for that class.
class MyClass
{
}
Now i am going to create a constructor for the above class and is given bellow.
class MyClass
{
MyClass // Constructor
{
}
}
Example:
class MyClass
{
String demo;
MyClass()
{
demo = "Demo value";
System.out.println("Constructor is invoked");
System.out.println("Assigned value is "+demo);
}
}
public class ConstructorDemo
{
public static void main(String args[])
{
MyClass m = new MyClass();
}
}
Output:
constructor keep the following points in mind.
1. The name of the constructor is same as the class name.
2. There is no return type for a constructor.
3. A constructor invokes automatically when we create an object of that class.
Suppose we have the following class and we need a constructor for that class.
class MyClass
{
}
Now i am going to create a constructor for the above class and is given bellow.
class MyClass
{
MyClass // Constructor
{
}
}
Example:
class MyClass
{
String demo;
MyClass()
{
demo = "Demo value";
System.out.println("Constructor is invoked");
System.out.println("Assigned value is "+demo);
}
}
public class ConstructorDemo
{
public static void main(String args[])
{
MyClass m = new MyClass();
}
}
Output: