jeudi 23 mars 2017

Java: Inheritance, BuilderPattern and Generics

I want to implement Builder Pattern with inheritance. So I have 4 following classes: one abstract class (ClassA), ClassB, ClassC. TestTest class is used to see how all this works:

public abstract class ClassA {

    private String aString;

    public String getaString() {
        return aString;
    }

    public abstract class ClassABuilder<T extends ClassABuilder>{

        public T setaString(String str) {
            ClassA.this.aString = str;
            return (T)this;
        }

        public abstract ClassA build();

    }
}

public class ClassB extends ClassA{

    private String bString;

    public String getbString() {
        return bString;
    }

    public class ClassBBuilder<T extends ClassBBuilder> extends ClassA.ClassABuilder<T>{

        public T setbString(String str) {
            ClassB.this.bString = str;
            return (T)this;
        }

        @Override
        public ClassB build(){
            return ClassB.this;
        }
    }
}

public class ClassC extends ClassB{

    private String cString;

    public String getcString() {
        return cString;
    }

    public static ClassCBuilder<ClassCBuilder> newBuilder(){
        return new ClassC().new ClassCBuilder();
    }

    public class ClassCBuilder<T extends ClassCBuilder> extends ClassB.ClassBBuilder<T>{

        public T setcString(String str) {
            ClassC.this.cString = str;
            return (T)this;
        }

        @Override
        public ClassC build(){
            return ClassC.this;
        }
    }
}

public class TestTest {

    public static void main(String[] args) {
        // TODO code application logic here
        ClassC C=ClassC.newBuilder()
                .setaString(null)
                .setbString(null)
                .setcString(null) //LINE XXX
                .build();
    }
}

The problem is that at TestTest at LINE XXX I get can't find symbol "setcString". What do I do wrong?

Aucun commentaire:

Enregistrer un commentaire