This has probably been asked a million times before, but I'm having trouble wrapping my head around writing a copy constructor on an abstract class with a bounded type parameter. I have some code that looks like this:
public abstract class Superclass<T> {
Set<? extends Variable<T>> vars;
public abstract Superclass<? extends T> copy();
class Variable<T> {
T value;
}
}
class Foo extends Superclass<Integer> {
public Foo copy() {
Foo _newFoo = Foo();
Set<FooVariable> _newVars = new HashSet<FooVariable>();
_newVars.addAll(this.vars);
_newFoo.vars = _newVars;
}
class FooVariable extends Variable<Integer> { /* ... */ }
}
class Bar extends Superclass<String> {
public Bar copy() {
Bar _newBar = Bar();
Set<BarVariable> _newVars = new HashSet<BarVariable>();
_newVars.addAll(this.vars);
_newBar.vars = _newVars;
}
class BarVariable extends Variable<String> { /* ... */ }
}
Since the copy method for both Foo and Bar is the same except for the variable types, I'd like to be able to move that code into a concrete method in the superclass. But I can't figure out (a) how to have the concrete public Superclass<? extends T> copy method return a Foo instance if called on a Foo and a Bar instance if called on a Bar and (b) populate the vars set with FooVariables or BarVariables as appropriate.
Can anybody please help and tell me what I'm missing? Thanks.
Constructors can be Generic, despite its class is not Generic.
Like C++, Java also supports a copy constructor. But, unlike C++, Java doesn't create a default copy constructor if you don't write your own.
The copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object. 2. Copy constructor takes a reference to an object of the same class as an argument.
In Java, a copy constructor is a special type of constructor that creates an object using another object of the same Java class. It returns a duplicate copy of an existing object of the class. We can assign a value to the final field but the same cannot be done while using the clone() method.
What about this kind of Superclass?
public abstract class Superclass<T> {
Set<? extends Variable<T>> vars;
public Superclass<? extends T> copy() {
Superclass<T> _newSuperclass = this.getNewInstance();
Set<Variable<T>> _newVars = new HashSet<Variable<T>>();
_newVars.addAll(this.vars);
_newSuperclass.vars = _newVars;
return _newSuperclass;
}
public abstract Superclass<T> getNewInstance();
class Variable<T> {
T value;
}
}
The point is that you just need to implement getNewInstance() in subclasses instead of constructor.
So Foo would look just like:
class Foo extends Superclass<Integer> {
@Override
public Superclass<Integer> getNewInstance() {
return new Foo();
}
class FooVariable extends Variable<Integer> { /* ... */ }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With