Java Default Constructor Example
public class Test1 {
public Test1() {
System.out.println("Inside default constructor...");
}
public static void main(String a[]) {
Test1 mdc = new Test1();
}
}
Parametarized Constructor
public class Test1 {
private String name;
public Test1(String str){
this.name = str;
System.out.println("Inside parameterized constructor.");
System.out.println("The parameter value is: "+str);
}
public static void main(String a[]){
Test1 mpc = new Test1("ACH");
}
}
Inside parameterized constructor.
The parameter value is: ACH
Constructor Overloading
public class Test1 {
private String name;
public Test1(){
System.out.println("Inside default constructor");
}
public Test1(int i){
System.out.println("Inside single parameter constructor with int value");
}
public Test1(String str){
System.out.println("Inside single parameter constructor with String object");
}
public Test1(int i, int j){
System.out.println("Inside double parameter constructor");
}
public static void main(String a[]){
Test1 t1 = new Test1();
Test1 t2 = new Test1(10);
Test1 t3 = new Test1(10,20);
Test1 t4 = new Test1("str");
}
}
Inside default constructor
Inside single parameter constructor with int value
Inside double parameter constructor
Inside single parameter constructor with String object
Constructor Chaining Sample Code
public
MyChaining(){
System.out.println(
"In default constructor..."
);
}
public
MyChaining(
int
i){
this
();
System.out.println(
"In single parameter constructor..."
);
}
public
MyChaining(
int
i,
int
j){
this
(j);
System.out.println(
"In double parameter constructor..."
);
}
public
static
void
main(String a[]){
MyChaining ch =
new
MyChaining(
10
,
20
);
}
In default constructor...
In single parameter constructor...
In double parameter constructor...
No comments:
Post a Comment