Professional Documents
Culture Documents
RCC Institute of Information Technology: Topic: A. Class and Object B. This
RCC Institute of Information Technology: Topic: A. Class and Object B. This
Class in Java
A class is a blueprint for the object. Before we create an object, we first need to define the class.
We can think of the class as a sketch (prototype) of a house. It contains all the details about the
floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.
Since many houses can be made from the same description, we can create many objects from a
class.
For our bicycle object, we can create the class as (screenshot attatched)
In the example, I have created a class named Bicycle. It contains a field
named gear and a method named braking().
Here, Bicycle is a prototype. Now, we can create any number of bicycles using
the prototype. And, all the bicycles will share the fields and methods of the
prototype.
a Classes and Objects
Object in Java
An entity that has state and behavior is known as an object e.g., apple, plant, monitor, etc.
It can be physical or logical (tangible and intangible). An object is called an instance of a Bicycle
class. For example, suppose Bicycle is a class then MountainBicycle, SportsBicycle, (class)
TouringBicycle, etc can be considered as objects of the class
this in Java
The 'this' keyword refers to the current object in a method or constructor. For example,
OUTPUT
In the above example, I created an object named obj of the class Main. I then print the reference to the object obj and this
keyword of the class.
Here, we can see that the reference of both obj and this is the same. It means this is nothing but the reference to the
current object.
b this
Usage
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 most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same
name (because a class attribute is shadowed by a method or constructor parameter). If you omit the keyword in the example
above, the output would be "0" instead of "5".
this can also be used to:
Invoke current class constructor
Invoke current class method
Return the current class object
Pass an argument in the method call
Pass an argument in the constructor call
For example,
In the above program, the instance variable and the parameter have the same name: age.
Here, the Java compiler is confused due to name ambiguity. In such a situation, we use this
keyword. For example,
First, let's see an example without using this keyword: Now, let's rewrite the above code using 'this' keyword.
OUTPUT OUTPUT
Now, we are getting the expected output. It is because when the constructor is called, this inside the constructor is replaced
by the object obj that has called the constructor. Hence the age variable is assigned value 8.
The End
Thank you