Reputation: 303
I am confused of calling a private method by another method(public) belonging to the same class.Once
I have been told I gotta create an object of that class and then call the private method via this object but in one of my questions in this forum I have been told that I dont need to use object.
public class Train() {
private void method1{......method definition..... }
public void method2{......how to invoke method1??}
}
Can I simply call the first method inside the second method by using method1();
or should I invoke it by creating an object of the class and Object_of_Train.method1();
.
Which one should I use?
Upvotes: 0
Views: 18517
Reputation: 54
You can access the private methods of a class using java reflection package.
**Step1 − Instantiate the Method class of the java.lang.reflect package by passing the method name of the method which is declared private.
Step2 − Set the method accessible by passing value true to the setAccessible() method.
Step3 − Finally, invoke the method using the invoke() method.**
Example
import java.lang.reflect.Method;
public class DemoTest {
private void sampleMethod() {
System.out.println("hello");
}
}
public class SampleTest {
public static void main(String args[]) throws Exception {
Class c = Class.forName("DemoTest");
Object obj = c.newInstance();
Method method = c.getDeclaredMethod("sampleMethod", null);
method.setAccessible(true);
method.invoke(obj, null);
}
}
Source : Tutorialpoint
Upvotes: -1
Reputation: 974
Use this.method1();
to call from method2() or any other non-static method in the class.
Upvotes: 0
Reputation: 1451
Within the class you should be able to call method1();
Outside the class you will need to call it from an instance of that class and will have access to public methods only
Upvotes: 2