in this code :
public class Main{
private void method()
{
System.out.println("inside method");
}
public static void main(String[] args) {
Main obj = new Main();
obj.method();
}
}
Why we can access the private method using an object from the class when we are in the class , while we cann’t do that outside the class ? (I mean what is the logical reason ?)
Another case is : the main method is static so why there is no compiler error complaining about “accessing non-static method from a static method “??
Because its private. The class itself can use its private properties and behaviours. The reason why the outside classes can’t use that is to stop outside classes to interfere in private matters. Simple ain’t it?
Here you are actually invoking the method using instance context. Try calling it without
objit will definitely complain. By the way, who said you can’t access non-static method from a static method. You actually can’t call non-static methods in static context.