waltermilner

Untitled

May 22nd, 2019
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.60 KB | None | 0 0
  1. // avoiding telescoping constructors using a non-static block
  2.  
  3. public class Test {
  4.  
  5.   int x;
  6.   int y;
  7.  
  8.   { // put common code here - all constructors execute this..
  9.     System.out.println("In non-static block, doing common code");
  10.     x = 4;
  11.   }
  12.  
  13.   Test() {
  14.     System.out.println("in no-arg constructor");
  15.     y = 5; // no-arg ctor makes y 5
  16.   }
  17.  
  18.   Test(int val) {
  19.     System.out.println("In int arg constructor");
  20.     y = val; // this makes y whatever we want
  21.   }
  22.  
  23.   public static void main(String[] d) {
  24.     Test t1 = new Test(); // x=4 y=5
  25.     Test t2 = new Test(6);// x=4 y=6
  26.  
  27.   }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment