How to prohibit the use of an incorrectly initiated facility in java



  • Let's say there are classes like this:

    class Parent {
        int p1, p2;
        public Parent(int p1, int p2){
            this.p1 = p1;
            this.p2 = p2;
        }
    
    public void printVars(){
        System.out.printf("%d %d", p1, p2);
    }
    

    }

    class Child extends Parent{
    public Child(int p1, int p2){
    super(p1, p2);
    }
    }

    But I need to be in cases where p1 > p2 No use of the class object Child
    I mean, in an attempt to do this:

    public class Main {

    public static void main(String[] args) {
    
        Child child = new Child(2, 1);
        child.printVars();
    }
    

    }

    make a mistake, for example.
    How do you do that?



  • Usually, in such cases, the inspection shall be added to the class designer:

    class Child extends Parent {
            public Child(int p1, int p2) {
                super(p1, p2);
                if(p1 > p2)
                    throw new IllegalArgumentException("p1 was greater than p2");
            }
        }
    

Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2