Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package SandBox2;
- public class Test {
- public static void main(String[] args) {
- System.out.println(new A.Builder<>().foo(1).build());
- System.out.println(new B.Builder<>().foo(1).bar("abc").build());
- System.out.println(new C.Builder<>().foo(1).bar("abc").baz(0.5).build());
- }
- }
- class A {
- public final int foo;
- public A(int foo) {
- this.foo = foo;
- }
- @Override
- public String toString() {
- return "A{" + "foo=" + foo + '}';
- }
- public static class Builder <T extends Builder<T>> {
- public int foo;
- public T foo(int foo) {
- this.foo = foo;
- return (T)this;
- }
- public A build() {
- return new A(foo);
- }
- }
- }
- class B extends A {
- public final String bar;
- public B(int foo, String bar) {
- super(foo);
- this.bar = bar;
- }
- @Override
- public String toString() {
- return "B{" + "foo=" + foo + ", bar='" + bar + '\'' + '}';
- }
- public static class Builder <T extends B.Builder<T>> extends A.Builder<T> {
- protected String bar;
- public T bar(String bar) {
- this.bar = bar;
- return (T)this;
- }
- public B build() {
- return new B(foo, bar);
- }
- }
- }
- class C extends B {
- public final double baz;
- public C(int foo, String bar, double baz) {
- super(foo, bar);
- this.baz = baz;
- }
- @Override
- public String toString() {
- return "C{" + "foo=" + foo + ", bar='" + bar + '\'' + ", baz=" + baz + '}';
- }
- public static class Builder <T extends C.Builder<T>> extends B.Builder<T> {
- protected double baz;
- public T baz(double baz) {
- this.baz = baz;
- return (T)this;
- }
- public C build() {
- return new C(foo, bar, baz);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement