0
How do invoke a method which you have created in the previous class created to another class you just created in java
calling method in a class to another class
2 Answers
+ 1
If the method is static, you can use
className.methodName
to access method for that class in your current class.
Example -
class A{
public static void hello() {
System.out.println("hello");
}
}
class TestClass {
public static void main(String args[] ) throws Exception {
A.hello();
}
}
If the method is not static, you need to create the object of that class in the current class and then use the method using the below syntax -
ThatClass thatClassObject = new ThatClass();
thatClassObject.methodName();
class A{
public void hello() {
System.out.println("hello");
}
}
class TestClass {
public static void main(String args[] ) throws Exception {
A a = new A();
a.hello();
}
}
0
1. declare that method as public.
2. Create an instance of that class
---------------------------------------------------
Student aStudent = new Student();
---------------------------------------------------
3. Call the method through the object
---------------------------------------------------
aStudent.GetName();
---------------------------------------------------
---------------------------------------------------
If the method is static
---------------------------------------------------
Student.GetTotalStudentCount();