oop - Accessing a private element through an inline created object in java -
i new java , trying accessing methods , encountered not understand. code below working fine, prints 9 , not giving compilation errors. think code should give compilation error , number should inaccessible test method, since new human() instance of totally different class. can explain me happening here ?
public class test{ public static void main(string[] args) { int number = 9; test("holla",new human(){ @override void test() { // todo auto-generated method stub system.out.println(number); // think line should not compile } }); } private static void test(string ,human h){ h.test(); } }
human class
public abstract class human { abstract void test(); }
this valid (for java8 - prior that, need thje final
keyword when declaring number
):
- you create anonymous inner class extends human , provides required implementation of
test()
method. - that method using variable enclosing "scope" - , compiler smart enough detect variable in fact constant - there no other subsequent assignments it.
in order "invalidate" example: add assignment
number = 42;
within main method - after defining anonymous inner class. or use version of java older java8.
keep in mind anonymous inner classes closures, , jvm copying values required "inside" outside. when outside value changes - value should copied. see here further reading.
wiki
Comments
Post a Comment