2
Dec
Method is the activity of an object. Different object can have different activities.
Method can be called in 2 ways.
a) object.method() and
b) class.method()
When object is initialize, then method should be called by object.method() approach.
When method need to called from class directly, then “static” keyword need to be used before method name. Generally class.method() approach applied when there is no constructor.
Example:
a) object.method() approach:
class Main {
public static void main(String[] args) {
Human human=new Human();
human.sing("Hrittik");
human.dance("Katrina");
}
}
class Human{
public String name;
//method
public void sing(String name){
System.out.println(name+" can sing");
}
//method
public void dance(String name){
System.out.println(name+" can dance");
}
}
b) class.method() approach:
class Main {
public static void main(String[] args) {
Human.sing("Hrittik");
Human.dance("Katrina");
}
}
class Human{
public String name;
//method
public static void sing(String name){
System.out.println(name+" can sing");
}
//method
public static void dance(String name){
System.out.println(name+" can dance");
}
}
Output:
Hrittik can sing
Katrina can dance
Leave a Reply