Advertisement
kajacx

Test

Jan 12th, 2014
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.05 KB | None | 0 0
  1. package test;
  2.  
  3. public class SO {
  4.  
  5.     public static void main(String[] args) {
  6.         for (MyInt mi : new MyInt[]{new PositiveInt(), new EvenInt()}) {
  7.             mi.setMyInt(5);
  8.             System.out.println(mi.getMyInt());
  9.             mi.setMyInt(-6);
  10.             System.out.println(mi.getMyInt());
  11.             mi.setMyInt(0);
  12.             System.out.println(mi.getMyInt());
  13.             System.out.println();
  14.         }
  15.     }
  16. }
  17.  
  18.     abstract class MyInt {
  19.  
  20.         private int myInt;
  21.  
  22.         public int getMyInt() {
  23.             return myInt;
  24.         }
  25.  
  26.         public void setMyInt(int i) {
  27.             myInt = checkMyInt(i);
  28.         }
  29.  
  30.         protected abstract int checkMyInt(int i);
  31.     }
  32.  
  33. //only positive values
  34. class PositiveInt extends MyInt {
  35.  
  36.     @Override
  37.     protected int checkMyInt(int i) {
  38.         if (i < 0) {
  39.             return -1;
  40.         }
  41.         if (i == 0) {
  42.             return 1;
  43.         }
  44.         return i;
  45.     }
  46. }
  47.  
  48. //only even values
  49. class EvenInt extends MyInt {
  50.  
  51.     @Override
  52.     protected int checkMyInt(int i) {
  53.         return 2 * (i / 2);
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement