Re: access levels for private field which is inherited
Lothar Kimmeringer wrote:
thufir wrote:
Would someone provide an example where Foo extends Bar and there are
private fields in Bar which Foo uses in its constructor(s)? Seems a
conundrum...Using the following example:
Without reflection there is no way, but given your example
you just need to call setName(name) to achieve your intention.
Even with reflection, is it possible? I was just playing around with
reflection and I noticed that the API only promises to return public
methods and fields. Maybe there's a sneaky "getAll" that I missed...
Anyway, calling super here is probably the best choice. Note than in
your example you must call super because Bar has no default constructor.
One can also provide a factory method such as newInstance below.
package attribs;
public class Foo extends Bar {
private String id;
public Foo(String name,String id){
super( name ); // New line here
//this.name = name; // Get rid of this one
this.id = id
}
static public Foo newInstance( String id ) {
Foo f = new Foo( "default", id );
f.setSomeOtherNonfinalProperty( "non" );
return f;
}
package attribs;
public class Bar {
private String name;
public setName(String name) {this.name = name;}
}