Constructor in Java
Constructor is used to initialize the property.
Constructor must be the class name.
Constructor must have an access modifiers.
Constructor never have any non-access modifiers.
Constructor always call by the new keyword.
Constructor never have any return type.
Constructor always return same type of object.
There are two type of Constructors :
- Default Constructor or Non-Parameterized Constructor
- Parameterized Constructor
1. Default Constructor or Non-Parameterized Constructor
class A{
}
//save and compile
//then using javap tool you can see default constructor like below :
C:\Users\Deep Singh\Desktop>javap A
Compiled from "A.java"
class A {
A();// this is a default constructor
}
//its access modifier is default
public class A{
}
//save and compile
//then using javap tool you can see default constructor like below :
C:\Users\Deep Singh\Desktop>javap A
Compiled from "A.java"
public class A {
public A();// this is a default constructor
}
class A{
//no-parameterized constructor
private A(){
}
}
class A{
protected A(){
}
}
//save and compile
//then using javap tool you can see default constructor like below :
C:\Users\Deep Singh\Desktop>javap A
Compiled from "A.java"
class A {
protected A();// there is no defualt constructor
}
class A{
int i;
public static void main(String [] h){
A a=new A();
System.out.println(a.i); // 0
}
}
/*If i does not contain any value so its
default value is based on its type so
it can be initialize by 0.*/
OR
class A{
int i=10;
public static void main(String [] h){
A a=new A();
System.out.println(a.i); // 10
}
}
/*If i contain any value so
it can be initialize by 10.*/
2. Parameterized Constructor
Parameterized constructor is used to get input from user for initializing user specific value.
class A{
int i;
A(int j){
i=j;
}
public static void main(String [] h){
A a=new A(20);
System.out.println(a.i); // 20
}
}
For Example :
class Student{
String name;
int roll;
Student(String n,int r){
name=n;
roll=r;
}
}
class Test{
public static void main(String [] h){
Student s=new Student("rahul",123);
System.out.println(s.name);
System.out.println(s.roll);
}
}
Output is : rahul
Output is : 123
No comments:
Post a Comment