Search code examples
javaclassscopeprivate

java - access private variables


Possible Duplicate:
Java private field access

I just observed little weird(imho) thing in java :

class foo{
    private int secret;
    public int getSecret(){
        return secret;
    }
    public void confuseCoder(foo o){
        System.out.println(o.secret);
    }
}

Same question was there ( Java private field access possible when having a reference? ) but I'm not sure if I can live with that feeling that someday, somewhere I will access wrong variable and it will destroy world or something.

Is there any way to restrict access to private variables at the class level ?

Thanks, Vojtěch


Solution

  • someday, somewhere I will access wrong variable and it will destroy world or something

    That is called being human, since java has no way to avoid this error the compiler wont catch it for you. The right way to avoid world destroying errors is to write tests and use other forms of quality management.

    While I think an experienced java programmer could write an Annotation Processor/compiler plugin to flag variables as instance private, there currently are no implementations I know of.