Constructors
Constructors
Syntax:
<class_name>()
{
}
Example 1
• //Java Program to create and call a default constructor
• class Bike1{
• //creating a default constructor
• Bike1()
• {
• System.out.println("Bike is created");
• }
• //main method
• public static void main(String args[]){
• //calling a default constructor
• Bike1 b=new Bike1();
• }
• }
• Output:
• Bike is created
Example 2
class Test
{
int a,b;
Test()
{
Output:
a=5; 5
b=6; 6
}
public static void main(String args[])
{
Test obj=new Test();
System.out.println(obj.a);
System.out.println(obj.b);
}
}
Default Constructor
class Student3{
int id;
String name;
Student3() 101 Rishwanth101
{ Rishwanth.
name="Rishwanth";
id=101;
}
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}
Java Parameterized Constructor
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Constructor Overloading in Java
class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all
instance data members will get memory each time when
the object is created. All students have its unique rollno and
name, so instance data member is good in such case. Here,
"college" refers to the common property of all objects. If
we make it static, this field will get the memory only once.
Example of static variable
Output:
111 Karan ITS
222 Aryan ITS
Program of the counter without static
variable
Output:
1
1
1
Program of counter by static variable
static variable will get the memory only once
Output:
1
2
3
Java static method