A extends B, may i reference B suboject in A's constructor?
public A(B b)
{
/*(B)this = b*/
}
If not, how do i construct an A object with a B object?, i mean other that using Cloneable to create some other instance or solutions out of the JLS (dozer, beanutils, etc.). In a nutshell, how would the A constructor look like to make this code to run?
B b = new B("hi");
A a = new A(b);
assertequals(a.getSalute(), "h开发者_StackOverflow中文版i");//ok so far
a.setSalute("hola");
assertequals(b.getSalute(), "hola");//A maintains a reference to B
f(a);//prints hola
f(b);//prints hola as well
Thanks in advance
It looks like you're trying some kind of decorator pattern. I'm not the biggest fan of "program to an interface" because I think it's good advice that's over-used, but I think this is a good situation for it.
interface Wrapable { // replace Wrapable with something more appropriate
// common methods here?
}
class B implements Wrapable {
}
class A implements Wrappable {
Wrappable whatThisWraps;
A(Wrappable w) { whatThisWraps = w; }
}
Yes. Java does not disallow forward references to concrete classes the way C++ does.
You do have to be aware though of static class initializers.
From DCL12-J. Prevent class initialization cycles:
According to §12.4, "Initialization of Classes and Interfaces" of the Java Language Specification [JLS 2005]
Initialization of a class consists of executing its
static
initializers and the initializers forstatic
fields (class variables) declared in the class.In other words, the presence of a
static
field triggers the initialization of a class. However, a static field could depend on the initialization of a class, possibly creating an initialization cycle. The Java Language Specification also states in §8.3.2.1, "Initializers for Class Variables" [JLS 2005]...at run time,
static
variables that arefinal
and that are initialized with compile-time constant values are initialized first.This statement can be misleading because it is inapplicable to instances that use values of
static final
fields that are initialized at a later stage. Declaring a field to bestatic final
is insufficient to guarantee that it is fully initialized before being read.
So long as your constructors are appropriately constructed, you can reference B in A's constructor as you described.
If A extends B, any A Object can be considered an B Object, but the reverse is not true.
To better answer your original question, creating a B from a A should be straightforward - change the A in the constructor to an B (since any A is also a B), call the appropriate getter methods and assign their values to the instance variables held by A. This type of constructor public B(B b)...
is a copy-constructor. If you decide to keep A in the constructor, then just apply the call/copy/assign logic mentioned by calling all methods inherited by A from B.
精彩评论