Mohamad Alhamoud
Mohamad Alhamoud

Reputation: 4929

Access private methods using objects

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

Upvotes: 3

Views: 3283

Answers (3)

Adam Robinson
Adam Robinson

Reputation: 185593

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).

Upvotes: 3

M.J.
M.J.

Reputation: 16646

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

Upvotes: 2

Adeel Ansari
Adeel Ansari

Reputation: 39887

  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.

Upvotes: 6

Related Questions