Page 270 - CA_Blue( J )_Class10
P. 270
}
void display()
{
System.out.println(name + " : " + dept);
ob1.display();
}
public static void main()
{
employee ob = new employee();
ob.take();
ob.display();
}
}
Explanation: In the above example, the object "ob" of class employee is created first. Then the take() method is called
which initializes the name and dept variables. After that the accept() method of the class salary is executed which
initializes the basic, da, hra, pf and gross variables. The object of class salary is ob1.
Similarly, the display() method of both the classes are called in the same manner.
11.7 CLASS AS AN OBJECT FACTORY
A factory usually produces a product of a similar kind. Similarly, a class in Java also creates several objects of the same
kind. A class being a prototype, no values can be assigned to it directly. We need to create objects of the class. These
objects contain attributes and behaviours of the class. Thus, a class is basically an object maker.
11.8 USING THIS KEYWORD
Sometimes, instance variables and the parameters passed to a method have the same name. These variables create
an anomaly as when the name is used in the program, then which one will be executed. In this situation, we can use
the name of the instance variable preceded by the word this keyword to access the instance variables. This keyword
denotes the current class’s object. For example:
class sum
{
int a, b, s; // a, b and s are instance variable
void accept (int a, int k) // a and k are parameters of accept () method
{
/* Value of parameter a is assigned to instance variable a. Since, both the variables
have the same name, that is why the keyword this is used before the instance
variable. */
this.a = a;
// Here, the keyword this is not used, as the variables are different.
b = k;
}
void display () {
s = a + b;
System.out.println("Result:" +s);
}
}
268268 Touchpad Computer Applications-X

