Can you tell us about your project.
Are both classes in the same package or not?
You just need to learn this topic of java tutorial:
Java call method from another class
The class calling the method needs a reference to the other class.
CallingMethod.java
MainClass.java
For getting access to CallingMethod class methods inside the class MainClass, an object of the CallingMethod class of CallingClass.java file has to created inside the class of MainClass.java file as shown in the example.
Syntax of creating object : ClassName objectName = new ClassName();
After creating object of CallingMethod.java file class CallingMethod inside the class of MainClass.java file. Its very easy to access the methods of the class CallingMethod. With just the object name along with a dot operator, any method at a time can accessed
Syntax for calling methods : objectName . methodName();
Note : Base directory of both the java files should match with each other.
Example:
Here is the code of CallingMethod.java
Code:
public class CallingMethod{
int c;
public int add(int a, int b){
return a+b;
}
public int subtract(int a, int b){
return a-b;
}
public int multiply(int a, int b){
return a*b;
}
public int division(int a, int b){
return a/b;
}
public int modulus(int a, int b){
return a%b;
}
}
Here is the code of MainClass.java
Code:
public class MainClass {
public static void main(String[] args){
CallingMethod method = new CallingMethod();
System.out.println("Addition: " + method.add(30,15));
System.out.println("Subtraction: " + method.subtract(30,15));
System.out.println("Multiplication: " + method.multiply(30,15));
System.out.println("Division: " + method.division(30,15));
System.out.println("Modulus: " + method.modulus(30,15));
}
}
Bookmarks