non-static inner class will fulfill all your desires:
public class Foo { protected String member; public Foo(String member) { this.member = member; } public class Bar { protected String member; public Bar(String member) { this.member = member; } public void show() { System.out.println("this.member: " + this.member + "; Foo.this.member: " + Foo.this.member); } } public static void main(String[] args) throws javax.mail.MessagingException, java.io.IOException { Foo foo_a = new Foo("a"); Foo foo_b = new Foo("b"); Bar bar_a1 = foo_a.new Bar("1"); Bar bar_a2 = foo_a.new Bar("2"); Bar bar_b1 = foo_b.new Bar("1"); Bar bar_b2 = foo_b.new Bar("2"); bar_a1.show(); bar_a2.show(); bar_b1.show(); bar_b2.show(); } }
Good, good, (-2 votes later):
Firstly, none of the above solutions concerns part of the original question that there cannot be exactly 1 file common to all objects. One group of objects may need to share file A, another group file B, etc. The inner class solution above is designed to fulfill exactly this requirement. You instantiate an outer class once for a file / group, and you create inner objects for a group from the same external object.
Secondly, static is a bad choice: it is likely that the file may need to be specified later at run time, and not when the program starts. The external / internal structure of the class above relates precisely to this problem. Whenever you need, you instantiate an outer class. Static initialization is not required (nor any complex schemes for deferred static initialization).
Thirdly, the thread of paranoia is simply not a problem in this problem (or this is a solution). It is quite clear that the file is read-only, therefore unchanged, therefore, all the simultaneous solution to the problem will only distract from elegant solutions.
Finally, speaking of elegance, this one, and probably the only one.
This update is mainly for someone new who comes in and looks at the stream, as negative voters in this stream are likely to get this down to -5.
source share