tags:

views:

53

answers:

3

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 "??

+5  A: 
  1. 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?

  2. Here you are actually invoking the method using instance context. Try calling it without obj it 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.

Adeel Ansari
+2  A: 

Answer to your second question :- you are invoking the method via object of that class, but if you will directly call the method it will give you an error, for accessing the non static method from static method.

And first one:- you are calling the method from inside the class, a class can use its private members

Mrityunjay
+2  A: 

Your confusion comes from a misunderstanding about what private means. The private keyword indicates that the member is accessible only from within the context of the declaring class`, not only from within the context of the containing instance. You are free to call private methods on yourself (the most common) or other instances of the same or a derived type (as you demonstrate).

There is no issue with calling instance methods from within a static method, but you must have an instance on which to call them (which you have as obj).

Adam Robinson