Important notes
- Constructors are invoked implicitly when you instantiate objects.
- The two rules for creating a constructor are:
- A Java constructor name must exactly match with the class name (including case).
- A Java constructor must not have a return type.
- If a class doesn't have a constructor, Java compiler automatically creates a default constructor during run-time. The default constructor initialize instance variables with default values. For example:
int
variable will be initialized to 0 - Constructor types:
- No-Arg Constructor - a constructor that does not accept any arguments
- Default Constructor - a constructor that is automatically created by the Java compiler if it is not explicitly defined.
- Parameterized constructor - used to specify specific values of variables in object
- Constructors cannot be abstract or static or final.
- Constructor can be overloaded but can not be overridden.
class Company {
String domainName;
public Company(){
this.domainName = "default";
}
public Company(String domainName){
this.domainName = domainName;
}
public void getName(){
System.out.println(this.domainName);
}
public static void main(String[] args) {
Company defaultObj = new Company();
Company programizObj = new Company("programiz.com");
defaultObj.getName();
programizObj.getName();
}
}
When you run the program, the output will be:
default programiz.com
No comments:
Post a Comment