java Constructor

Constructor

  • A constructor is a special member function used for automatic initialization if an object.
  • constructor are used for initializing values to the member data element of a class. data member means variable.
class student{
student(){
String name=”devil”;
}
}
  • student is a class and the constructor is student() .
  • constructor is same name as the class name
  • constructor can not be override.
Demonstration of CONSTRUCTOR programme of java
public class Student {
String name=”Devil”;
int rno;
Student(){
rno=526;
System.out.println(“constructor of student class initializing the value of roll no is: “+rno);
}
public static void main(String[] args)
{
new Student();
}
}

output :constructor of student class initializing the value of roll no is : 526
Note : no need to create object for the class just call them using new keyword object .

Overloading constructor Programme of java
public class AddNumber {
int x=3;
int y=6;
AddNumber(){
int sum;
sum=x+y;
System.out.println(“sum is without parameter constructor is :”+sum);
}
AddNumber(int a, int b){
int sum=a+y;
System.out.println(“sum with parameter constructor is :”+sum);
}
public static void main(String[] args){
new AddNumber();
new AddNumber(4,6);
}
}

output :sum is without parameter constructor is :9
sum with parameter constructor is :10

BACK

NEXT