- A constructor is a method with same name as class with no return type.
- Whenever we instantiate a class we invoke the constructor.
- This constructor then instantiates the objects.
- Every class has a constructor by default.
- We can also do constructor overloading.
- Example of Constructor with overloading is given below
package javaimplant.constructor;
public class ConstructorExample
{
private String name;
public ConstructorExample()
{
System.out.println("Please also initialize name");
}
public ConstructorExample(String name) {
super();
this.name = name;
System.out.println("Initialized with name "+name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
ConstructorExample c=new ConstructorExample("Gaurav");
}
}
cc
No comments:
Post a Comment