Classes & Objects
27-01-25
Lecture 4C
Prof. Anita Agrawal
BITS-Pilani, K.K. Birla Goa campus
CONSTRUCTOR
2
Anita Agrawal 1/27/2025 10:35:34 AM
• Used for initializing new objects.
• Initializes an object immediately upon
creation
• The code creating the instance will have
a fully initialized usable object
immediately
Constructor 3
Anita Agrawal 1/27/2025 10:35:34 AM
• Has the same name as the class in which it
resides
• Has optional parameter list
• Has no return type, not even void.
Constructor contd…. 4
Anita Agrawal 1/27/2025 10:35:34 AM
Syntax:
class_name variable_name = new class_name();
Dog dog1= new Dog();
• Parentheses after the class name calls the
constructor
• If no constructor is defined for a class, java
creates a default constructor
5
Anita Agrawal 1/27/2025 10:35:34 AM
class rect
{
int rlength, rbreadth;
rect() //this is a constructor
{
rlength=10;
rbreadth=20;
}
}
Constructor Example 6
Anita Agrawal 1/27/2025 10:35:34 AM
this keyword 7
Anita Agrawal 1/27/2025 10:35:34 AM
• this keyword in Java is a reference
variable that refers to the current object of
a method or a constructor.
• During code execution when an object calls
the method or constructor ‘Maruti ‘, the
keyword 'this' is replaced by the object
handler "obj.“
8
•
Anita Agrawal 1/27/2025 10:35:34 AM
this.no_of_airbags= no_of_airbags;
obj.no_of_airbags = no_of_airbags;
Instance variables local variables
9
Anita Agrawal 1/27/2025 10:35:34 AM
• this. Mileage will be now replaced with
obj. mileage and similarly for the other
one.
• The main purpose of using this keyword in
Java is to remove the confusion between
class attributes and parameters that have
same names.
10
Anita Agrawal 1/27/2025 10:35:34 AM
Next……static and access specifiers 11
Anita Agrawal 1/27/2025 10:35:34 AM