Search code examples
javaprivate-class

JAVA - Beginner - Can a private class attribute be accessed outside of the class?


I am relatively new to Java OO Programming, and have reviewed the questions similar to this, although they don't seem to answer my question directly.

Basically, I understand that if a data member within a class is declared as private, then it is only accessible from within that same class.

My lecturer always advises that ALL attributes should be declared as private - why is this?

Now I am familiar with using GET methods, and my question is, can a private attribute be accessed outside of it's own class via invoking a PUBLIC 'get' method (which returns the aforementioned attribute) from another class?

For example:

public class Class()
{

    private int number = 0;

    public Class()
    {
    }

    public int getNumber()
    {
        return number;
    }

}

And then from another class:

public class Class2()
{

    Class class = new Class();

    public void showNumber()
    {
        System.out.print(class.getNumber());
    }
}

Will the second block of code allow the method in showInt() inside Class2 to actually access the private attribute from Class?

I guess I am really struggling with deciding whether any attribute or method should be declared public or private in general..

Is there any particular rule of thumb that should be followed?

Thank you responders for any assistance.

Kind regards


Solution

  • Yes, if you make a public accessor, you may access the private field.

    The point is to hide the implementation so that, as an implementor, you may decide later to have another type of field (or an indirection, or a dynamic computation) without forcing the users of your class to change their code.

    It also lets you offer a getter while not offering any setter (then your field is read only from outside the class).

    Many things wouldn't compile in your code :

    • add parenthesis to call a method (getInt)
    • class is a reserved word
    • a class can't be called Class and isn't declared as you did

    I'd suggest you write a compiling code in an editor (e.g. Eclipse) before asking a question. This task would probably help you understand at least part of the problems.