0% found this document useful (0 votes)
11 views18 pages

Constructor&This

The document explains the different types of variables in Java: local, instance, and static variables, along with their characteristics. It also covers constructors, including default and parameterized constructors, and their rules and purposes. Additionally, it discusses constructor overloading and the use of the 'this' keyword for referencing current class instances and invoking constructors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views18 pages

Constructor&This

The document explains the different types of variables in Java: local, instance, and static variables, along with their characteristics. It also covers constructors, including default and parameterized constructors, and their rules and purposes. Additionally, it discusses constructor overloading and the use of the 'this' keyword for referencing current class instances and invoking constructors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

1) Local Variable

A variable declared inside the body of the method is called local variable. You
can use this variable only within that method and the other methods in the class
aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called
an instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not
shared among instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local.
You can create a single copy of the static variable and share it among all the
instances of the class. Memory allocation for static variables happens only once
when the class is loaded in the memory.
Constructors in Java
 In Java, a constructor is a block of codes similar to the method. It is called
when an instance of the class is created. At the time of calling constructor,
memory for the object is allocated in the memory.
 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.
 There are two types of constructors in Java: no-arg constructor, and
parameterized constructor.
Note: It is called constructor because it constructs the values at the time of
object creation. It is not necessary to write a constructor for a class. It is because
java compiler creates a default constructor if your class doesn't have any.

Rules for creating Java constructor


There are two rules defined for the constructor.
 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized
 We can use access specifiers while declaring a constructor. It controls the
object creation. In other words, we can have private, protected, public or
default constructor in Java.

Types of Java constructors


There are two types of constructors in Java:
 Default constructor (no-arg constructor)
 Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any
parameter
//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
If there is no constructor in a class, compiler automatically creates a default
constructor.

What is the purpose of a default constructor?


The default constructor is used to provide the default values to the object like 0,
null, etc., depending on the type.

Example :
//Let us see another example of default constructor
//which displays the default values
class Student3{
int id;
String name;
//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();
}
}

Output :
0 null
0 null

Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor. Here 0 and null values are provided by
default constructor

Example :
class Student {
String firstName;
int age;

//Student constructor
Student(){
firstName = "Raj";
age = 100;
}
public static void main(String args[]) {
Student myStudent = new Student();
System.out.println(myStudent.firstName);
System.out.println(myStudent.age);
}
}
Output :
Raj
100

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a
parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct
objects. However, you can provide the same values also.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
//Java Program to demonstrate the use of the 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


In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
Constructor overloading in Java
is a technique of having more than one constructor with different parameter
lists. They are arranged in a way that each constructor performs a different task.
They are differentiated by the compiler by the number of parameters in the list
and their types.
//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Output
111 Karan 0
222 Aryan 25

Java Copy Constructor


There is no copy constructor in Java. However, we can copy the values from
one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in Java. They
are:
 By constructor
 By assigning the values of one object into another
 By clone() method of Object class
In this example, we are going to copy the values of one object into another
using Java constructor.
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}

Output
111 Karan
111 Karan

Copying values without constructor


We can copy the values of one object into another by assigning the objects
values to another object. In this case, there is no need to create the constructor.

class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}

Output:
111 Karan
111 Karan
this keyword in Java
There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.

.
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves
the problem of ambiguity.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output
111 Karan 5000.0
112 Sumit 6000.0

It is better approach to use meaningful names for variables. So we use same


name for instance variables and parameters in real time, and always use this
keyword.

2) this: to invoke current class method


You may invoke the method of the current class by using the this keyword. If
you don't use the this keyword, compiler automatically adds this keyword while
invoking the method.
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}

Output
hello n
hello m

3) this() : to invoke current class constructor


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.
Calling default constructor from parameterized constructor:
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 n
10

Calling parameterized constructor from default constructor:


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 n

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.
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=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();
}}

111 ankit java 0.0


112 sumit java 6000.0

Call to this() must be the first statement in constructor.

You might also like