Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>a non-static inner class will fulfill all your desires:</p> <pre><code>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(); } } </code></pre> <p>Well, well, well, (-2 votes later):</p> <p>Firstly, none of the above solutions address the part of the original question that there may not be exactly 1 file shared by all objects. One group of objects may need to share file A, and another group file B, and so forth. The inner class solution above is intended to fulfill exactly that requirement. You instantiate the outer class once per file/group, and you instantiate inner objects for a group from the same outer object.</p> <p>Secondly, static is a poor choice: it is quite likely that the file might need to be specified later during the run-time rather than at program startup. The outer/inner class structure above addresses exactly that issue. You instantiate the outer class whenever you need to. No static initialization is needed (nor any complicated schemes for deferred static initialization).</p> <p>Thirdly, thread paranoia was simply not an issue in this problem (or this solution). It is pretty clear that the file is a read-only, hence immutable, so going all concurrent on the problem will only detract from elegant solutions.</p> <p>Finally, speaking of elegant, this one is, and probably the only one.</p> <p>This update is mostly for someone new who comes and looks at the thread, since the negative voters in this thread will probably get this to -5.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload