Java Program to Call Method in Same Class

This Java program is used to call method in same class.

Example:
public class CallingMethodsInSameClass
{
 // Method definition performing a Call to another Method
 public static void main(String[] args) {
  Method1(); // Method being called.
  Method2(); // Method being called.
 }

 // Method definition to call in another Method
 public static void Method1() {
  System.out.println("Hello World!");
 }

 // Method definition performing a Call to another Method
 public static void Method2() {
  Method1(); // Method being called.
 }
}
Program Output:

CallingMethodsInSameClass

Explanation:

This program demonstrates how programmers can call a method from within the same class. In this program, you have to first make a class name 'CallingMethodsInSameClass' inside which you call the main() method. This main() method is further calling the Method1() and Method2(). Now you can call this as a method definition which is performing a call to another lists of method.

Now inside the main, the Method1 and Method2 gets called. In the next consecutive lines, the Method1() is defined having access specifier 'public' and no return type i.e. 'void'. Inside that Method1() a statement is being coded which will print Hello World!. Similarly another method which is Method2() is being defined with 'public' access specifier and 'void' as return type and inside that Method2() the Method1() is called.

Hence, this program shows that a method can be called within another method as both of them belong to the same class.


Here are few other related articles for you to read:

Courses
Subscribe Updates via Email

Join 49,000+ W3schools lovers and get all the latest tutorials, programs, algorithms in your inbox.