Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package test;
- public class SO {
- public static void main(String[] args) {
- for (MyInt mi : new MyInt[]{new PositiveInt(), new EvenInt()}) {
- mi.setMyInt(5);
- System.out.println(mi.getMyInt());
- mi.setMyInt(-6);
- System.out.println(mi.getMyInt());
- mi.setMyInt(0);
- System.out.println(mi.getMyInt());
- System.out.println();
- }
- }
- }
- abstract class MyInt {
- private int myInt;
- public int getMyInt() {
- return myInt;
- }
- public void setMyInt(int i) {
- myInt = checkMyInt(i);
- }
- protected abstract int checkMyInt(int i);
- }
- //only positive values
- class PositiveInt extends MyInt {
- @Override
- protected int checkMyInt(int i) {
- if (i < 0) {
- return -1;
- }
- if (i == 0) {
- return 1;
- }
- return i;
- }
- }
- //only even values
- class EvenInt extends MyInt {
- @Override
- protected int checkMyInt(int i) {
- return 2 * (i / 2);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement