Advertisement
Guest User

Untitled

a guest
Oct 29th, 2021
442
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | None | 0 0
  1. package SandBox2;
  2.  
  3. public class Test {
  4.     public static void main(String[] args) {
  5.         System.out.println(new A.Builder<>().foo(1).build());
  6.         System.out.println(new B.Builder<>().foo(1).bar("abc").build());
  7.         System.out.println(new C.Builder<>().foo(1).bar("abc").baz(0.5).build());
  8.     }
  9. }
  10.  
  11. class A {
  12.     public final int foo;
  13.  
  14.     public A(int foo) {
  15.         this.foo = foo;
  16.     }
  17.  
  18.     @Override
  19.     public String toString() {
  20.         return "A{" + "foo=" + foo + '}';
  21.     }
  22.  
  23.     public static class Builder <T extends Builder<T>> {
  24.         public int foo;
  25.  
  26.         public T foo(int foo) {
  27.             this.foo = foo;
  28.             return (T)this;
  29.         }
  30.  
  31.         public A build() {
  32.             return new A(foo);
  33.         }
  34.     }
  35. }
  36.  
  37. class B extends A {
  38.     public final String bar;
  39.  
  40.     public B(int foo, String bar) {
  41.         super(foo);
  42.         this.bar = bar;
  43.     }
  44.  
  45.     @Override
  46.     public String toString() {
  47.         return "B{" + "foo=" + foo + ", bar='" + bar + '\'' + '}';
  48.     }
  49.  
  50.     public static class Builder <T extends B.Builder<T>> extends A.Builder<T> {
  51.         protected String bar;
  52.  
  53.         public T bar(String bar) {
  54.             this.bar = bar;
  55.             return (T)this;
  56.         }
  57.  
  58.         public B build() {
  59.             return new B(foo, bar);
  60.         }
  61.     }
  62. }
  63.  
  64. class C extends B {
  65.     public final double baz;
  66.  
  67.     public C(int foo, String bar, double baz) {
  68.         super(foo, bar);
  69.         this.baz = baz;
  70.     }
  71.  
  72.     @Override
  73.     public String toString() {
  74.         return "C{" + "foo=" + foo + ", bar='" + bar + '\'' + ", baz=" + baz + '}';
  75.     }
  76.  
  77.     public static class Builder <T extends C.Builder<T>> extends B.Builder<T> {
  78.         protected double baz;
  79.  
  80.         public T baz(double baz) {
  81.             this.baz = baz;
  82.             return (T)this;
  83.         }
  84.  
  85.         public C build() {
  86.             return new C(foo, bar, baz);
  87.         }
  88.     }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement