Experiment 6
Experiment 6
: 06
Title: Program to define class and constructors. Demonstrate constructors with this keyword.
Theory:
It is a special type of method which is used to initialize the object. Every time an
object is created using the new() keyword, at least one constructor is called. It calls a default
constructor if there is no constructor available in the class. In such case, Java compiler
provides a default constructor by default.
<class_name>(){}
Bike is created
The default constructor is used to provide the default values to the object like 0, null,
etc., depending on the type.
Program 2:
Output
0 null
0 null
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);
}
Output
111 Karan
222 Aryan
There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object. The this() constructor call can be used to invoke the
current class constructor. It is used to reuse the constructor. In other words, it is used for
constructor chaining.
Program 4: Calling default constructor from parameterized constructor
public class A {
A(){
System.out.println("hello a");
}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){ A a=new A(10);
}
}
Output
hello a
10
public class A {
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}
}
Output
5
hello a
Real usage of this() constructor call
The this() constructor call should be used to reuse the constructor from the
constructor. It maintains the chain between the constructors i.e. it is used for constructor
chaining. Let's see the example given below that displays the actual use of this keyword.
Program 6:
class Student{
int rollno;
String name,course;
float fee;
void display(){
System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}
}
Output