Page 261 - Computer science 868 Class 12
P. 261
The output of the preceding program is as follows:
Enter name: Partha Saha
Enter annual income: 700000
Name Income Tax
Partha Saha 70000.0
Difference between constructor and method
Constructor Simple Method
1. It is used to initialise the instance variables of 1. It is used to execute the Java code which performs
the object. a specific job.
2. It can be invoked only once at the time of 2. It can be invoked as many times as required for
creating the object. the same object.
3. Always have the same name as that of the class. 3. Class name and method name cannot be the same.
4. It does not have a return type. 4. It always have a return type. If the method does
not return a value, then void is mentioned.
8.13 this OPERATOR
Sometimes, in a method, the class attributes and the parameters sent to the method have the same name. there creates
an anomaly as when the name is used in the program, then which one will be executed. In this situation, to access the
class attributes we use the name of the variable preceded by the word “this” which specifically means the current object.
For example,
class rectangle
{
int len,bre,area,perimeter;
void accept (int len, int bre)
{
/* Values of parameters len and bre are assigned to instance variables len and bre.
Since both the variables and parameters are the same", that is why "this" keyword
is used before the instance variable else the compiler will get confused.*/
this.len=len;
this.bre=bre;
}
void calculate()
{
area = len * bre;
perimeter = 2 * (len +bre);
}
void display()
{
System.out.println("Area : " +area);
System.out.println("Perimeter : " + perimeter);
}
}
8.14 ALGORITHMIC PROBLEM SOLVING USING METHODS
1. Write an algorithm to calculate and print the factorial of a number in a method called factorial(int).
n! = 1 × 2 × 3 × 4 × ……… × n
Algorithm:
Step 1: Start.
Step 2 : Call the method factorial with a number n
259
Methods 259

