Different Ways of Calling Methods in JAVA
There are three different ways of calling a method in JAVA :-
- Use of static method
- Without static method and inside same class
- Without static method and inside another class
1. Use of static method
When we use a static method we can call the method without creating an object of the class.
//Use of static method class m1 { public static void main(String args[]) { //No object of class is created display(); } static void display() { System.out.println("Use of static method"); } }
Output
2. Without static method and inside same class
When we use a method without staticĀ keyword we need to create an object of the class.
//Without static method and inside same class class m2 { public static void main(String args[]) { //object of class is created m2 obj = new m2(); obj.display(); } void display() { System.out.println("Without static method and inside same class"); } }
Output
3. Without static method and inside another class
When we use a static method we can call the method without creating an object of the class. When the method is in a different class then we need to create an object of the class where the method resides.
//Without static method and inside another class class m3 { public static void main(String args[]) { //object of class is created //where method resides show obj = new show(); obj.display(); } } class show { void display() { System.out.println("Without static method and inside another class"); } }