Calling Java Methods from Other Classes

Methods and functions are a set of instructions that come into action when someone calls them. A method can have various instructions that are combined to perform a specific task. The code specified within the method is executed when it is called.

We have two types of methods in Java: user-defined and pre-defined. A user-defined method is a method that is defined inside the class to perform a specific function. In contrast, pre-defined methods can be called and used anywhere in the program without defining them.

A method can be invoked within the same class or from another class in Java. Any method, whether user-defined or pre-defined, is called using the dot syntax. This article has been tailored to present an in-depth overview of how a method in Java can be called from another class with the aid of examples.

Parts of a method

  1. Modifiers: There are four types of modifiers in Java: public, private, protected, and default. Static is a non-access modifier. Modifiers can change the behavior of a class. A method can have one or more modifiers attached to it.
  2. Return Type: Each method has a return type. Return type refers to the information returned to the caller after the work has been completed. If nothing is to be returned, it can be set to void
  3. Method name: This is a must since the method won’t be called without a name. A method name begins with an alphabet, not a special character or numeral. An underscore is an example of a special character.
  4. Argument List: If the method calls for any information from the caller for a task to be performed, you can state one or more arguments. The arguments are provided in a list that is contained in the parenthesis, where an argument name follows the argument type. Commas separate multiple arguments.
  5. Exception list: This is a list that shows the exceptions that will be encountered by the method.
  6. Method body: This is a code that defines the tasks that a method is supposed to perform. It is always enclosed in curly braces.

Calling a method from another class in Java

Method 1: How to call a default method from another class in Java

In case the method has no modifier, it is taken as default. To call a default method of another class, you need to have the class’s object. A default method can be accessed from within and not outside the package. This method is more accessible than the private method but more restrictive when compared to protected and public methods. Let us use a “School” class which has a method named “getName()”. To access this method from the second class, let’s say “Testing,” we use the object of the Student class. The program below is used to clarify how a default method can be called from another class.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>class School{
	String name;
	School(String name){
		this.name = name;
	}
	public String getName() {
		return this.name;
	}
}
public class Testing {
	public static void main(String[] args) {
// creating an object of the class School
		School school = new School("Cheptikit");
// calling the method getName of the class School
		String name = school.getName();
		System.out.println("The school name is : "+name);
	}
}</pre>
</div>

Output

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>The school name is : Cheptikit</pre>
</div>

Method 2: How to call a static method in Java from another class

In this scenario, we call a static method of another class. We do not need to create objects to call a method in the case of a static method since a static method can be accessed directly with a class name without creating an object of that class. A static method directly accesses static data. However, it requires an object to access the instance. The example below illustrates how to call a static method from another class in Java.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>class School{
	static String name;
	static String getName() {
		return name;
	}
}
public class Testing {
	public static void main(String[] args) {
		School.name = "Cheptikit";
		String name = School.getName();
		System.out.println("The School name is : "+name);
	}
}</pre>
</div>

Output

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>The School name is : Cheptikit</pre>
</div>

Method 3: How to call a protected method from another class in Java

If a method of a class has been declared as protected, it can only be called in another class if that class is a sub-class of the class that has the protected method. The protected method provides more accessibility compared to the private method. The program below clarifies how to access a protected method from another class.
In this case, we extend the “School” class to the “Testing” class and call the getName() method while using the object of the “Testing” class. Let us clarify this by using an example.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>class School{	
	protected String name;
	protected String getName() {
		return this.name;
	}
}
public class Testing extends School{	
	public static void main(String[] args) {
// creating an object of Class Testing
	    Testing tt = new Testing();
		tt.name = "Cheptikit";
// calling getName() method of class School
		String name = tt.getName();
		System.out.println("The School name is : "+name);
	}
}</pre>
</div>

Output

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>The School name is : Cheptikit</pre>
</div>

Method 4: How to call a public method from another class in Java

A method is called public if it can be called into another class and if it is available for outside access. The public method can be accessed from either within or outside the package.
The example below shows how to access the public method from another class.
In this example, let us call a public method named getName() into another class with the aid of the School class:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>class School{	
	public String name;
	public String getName() {
		return this.name;
	}
}
public class Testing{
	public static void main(String[] args) {
// creating an object of the Class School
		School sch = new School();
		sch.name = "Cheptikit";
// calling the getName method of the School Class
		String name = sch.getName();
		System.out.println("The School name is : "+name);
	}
}</pre>
</div>

Output

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>The School name is : Cheptikit</pre>
</div>

Method 5: How to call a private method from another class in Java

A private method has more accessibility restrictions compared to other methods. A private method can be called from any class with the aid of java.lang.Class and java.lang.reflect.Method by using getDeclareMethod(), setAccessible(), and invoke() methods. The program below illustrates how to call a private method from another class. Private methods cannot be called into any other class because they are limited to the same class.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.lang.reflect.Method;
class School {
  // Private method
  private void printData() {
    System.out.println("Cheptikit is the best Elementary School");
  }
}
public class Example {
  public static void main(String[] args) throws Exception {
    School sch = new School();
    // Using getDeclareMethod() method
    Method m = School.class.getDeclaredMethod("printData");
    // Using setAccessible() method
    m.setAccessible(true);
    // Using invoke() method
    m.invoke(sch);
  }
}</pre>
</div>

Output

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>Cheptikit is the best Elementary School</pre>
</div>

Conclusion

A method is accessible from another class based on the access modifier. For instance, a method that is created with a public modifier can be called from inside or outside the class. By using inheritance, a protected method can be invoked from another class, whereas a static method can be invoked from some other class by using the class name. Private methods can’t be called into any class since they are limited to the same class. This article considered various examples in explaining how to call a method from another class in Java. I hope it helps you solve your puzzle.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *