Static Methods – Accessing Private Members in Object-Oriented Programming

language-featuresobject-orientedstatic methods

The following is pseudo code, I tried it in Java and PHP and both worked:

class Test { 

    private int a = 5;

    public static function do_test(){
        var t = new Test();
        t.a = 1;
        print t.a // 1
    }

}

Test::do_test();

Why can you do this in OOP paradigm and what's the use of it?

Best Answer

In Java, private variables are visible to the whole class. They can be accessed from static methods and from other instances of the same class.

This is, for example, useful in factory methods. A factory method usually does initializations to an object which are so complex that you do not want to leave them to the application code. In order to do the initialization, the factory method often needs access to the class-internals you don't want to expose. Being able to access the private variables directly makes your life much easier.

However, when you would like to hide the implementation details of a class even from static methods or from other instances of that class, you could follow the private class data pattern. Put all private variables of a class into a private inner class and delegate any getters or setters to getters and setters of that inner class.

Another option is to define an interface for the class which declares all the public methods of the class and then only reference the class under that interface whereever possible. A reference to the interface-type can not be used to directly access anything not declared in the interface, no matter where (except with reflection, of course). When your use an object-oriented programming language which has no interfaces (like C++, for example), they can be simulated with an abstract base-class which is inherited by the actual class.

interface ITest {
     public int getA();
}

class Test implements ITest { 

    private int a = 5;

    public int getA() { return a; } // implementation of method declared in interface

    public static void main(){
        ITest t = new Test();
        t.a = 1; // syntax error: Interface ITest has no "a"
        System.out.println(t.getA()); // calls Test.getA, visible because ITest declares it
    }

}