Reputation: 85
Is it possible to add a @ decorator to a parent class's field or method without hiding it (without using super)?
Code below produces:
colA = null, colA = Hello World, ttl = 360
notice the toString has null for the parent
abstract class TableA {
protected String colA;
public String toString() {
return "colA = " + this.colA;
}
}
class TableAImpl extends TableA {
//@Computed("ttl(value)")
int myTtl;
//*** NOTICE THIS ***
//@PartitionKey
protected String colA;
public TableAImpl(int ttl, String colA) {
this.myTtl = ttl;
this.colA = colA;
}
//*** NOTICE THIS ***
public String toString() {
return super.toString() + ", colA = " + this.colA + ", ttl = " + this.myTtl;
}
}
public class HelloWorld{
public static void main(String []args){
TableAImpl a = new TableAImpl(360, "Hello World");
System.out.println(a.toString());
}
}
Context:
I need to support multiple database types so I have a generic Entity class which are overloaded by DB specific Implementation classes. These DB specific classes overload/add the specific logic to interface with that DB, which should be invisible to the caller.
For one of the DBs used, the java driver's logic is primarily done by adding @Decorators to the Entity Class's methods and attributes which it uses to generate helper code.
When I try the below code to add decorators to them, the child class's variables hide the parent's
Upvotes: 0
Views: 168
Reputation: 2265
You've never set parent's colA
attribute.
public TableAImpl(int ttl, String colA) {
this.myTtl = ttl;
this.colA = colA;
super.colA = colA;
}
To protect parent's colA
you should set it private with private
and a getter
like so :
abstract class TableA {
private String colA;
public TableA() {}
public TableA(String colA) {
this.colA = colA;
}
public String toString() {
return "colA = " + this.colA;
}
protected String getColA() {
return colA;
}
}
class TableAImpl extends TableA {
//@Computed("ttl(value)")
int myTtl;
public TableAImpl(int ttl, String colA) {
super(colA);
this.myTtl = ttl;
}
public String toString() {
return super.toString() + ", colA = " + this.getColA() + ", ttl = " + this.myTtl;
}
//*** NOTICE THIS ***
//@PartitionKey
@Override
public String getColA() {
return super.getColA();
}
}
public class Main{
public static void main(String []args){
TableAImpl a = new TableAImpl(360, "Hello World");
System.out.println(a.toString());
// colA = Hello World, colA = Hello World, ttl = 360
}
}
Upvotes: 2