Page 232 - Computer science 868 Class 12
P. 232
8.4 DIFFERENT TYPES OF METHODS
The different types of methods are as follows:
1. Static method: Static methods have the keyword 'static' written along with the method prototype. When a method
is declared static, it means it belongs to the class instead of the object/instance of the class. The advantage of
declaring static is that it can access the static data members. The static methods are invoked by using the class
name.
For example:
class calculate
{
static int a;
static void print()
{
a=5;
System.out.println("The result :"+a);
}
}
Note: 'Static int a' is said to be a class variable. This variable is created once and different objects of the
class will be able to access that the variable. If there is any change in value of the variable, then it will be
reflected on all objects.
Let us see the use of a static variable.
class student_number
{
static int count=0; //will get memory each time when the instance is created
student_number()
{
count++; //incrementing roll number
System.out.println("Roll Number "+ count);
}
public static void main(String args[])
{
//Creating objects
student_number st1=new student_number();
student_number st2=new student_number();
student_number st3=new student_number();
}
}
Output:
Roll Number 1
Roll Number 2
Roll Number 3
The above program counts number of student_=number objects created.
2. Instance Method: If a method is declared under a class without being preceded by the word static, then it becomes
the method of the instance of the class. To call the method, it becomes necessary to create an object of the class.
class method
{
230230 Touchpad Computer Science-XII

