Page 357 - CITS - Computer Software Application -TT
P. 357
COMPUTER SOFTWARE APPLICATION - CITS
• changing the number of arguments.
• or changing the data type of arguments.
• It is not method overloading if we only change the return type of methods. There must be differences in the
number of parameters.
Constructors and Overloaded constructors
Java Constructors
A constructor in Java is similar to a method that is invoked when an object of the class is created.
Unlike Java methods, a constructor has the same name as that of the class and does not have any return type.
For example,
class Test {
Test() {
// constructor body
}
}
Example: Java Constructor
class Main {
private String name;
// constructor
Main() {
System.out.println(“Constructor Called:”);
name = “Programiz”;
}
public static void main(String[] args) {
// constructor is invoked while
// creating an object of the Main class
Main obj = new Main();
System.out.println(“The name is “ + obj.name);
}
}
Output:
Constructor Called:
The name is Programiz
Types of Constructor
In Java, constructors can be divided into three types:
1 No-Arg Constructor
2 Parameterized Constructor
3 Default Constructor
344
CITS : IT&ITES - Computer Software Application - Lesson 94 - 100