Tanvi Jaywant
Tanvi Jaywant

Reputation: 415

How to overload a class

Initially, I had a Plan class which behaves like this:

class Plan {
     public enum Type {
         FOO
     }

     String checkFoo() {
        // some check for foo
     } 

     String doSomething() {
     }
} 

Now, I need to add another type called Bar.

class Plan {
     public enum Type {
         FOO, BAR
     }

     String checkFoo() {
        // some check for foo
     } 

     String checkBar() {
       // some check for bar
     }   

      String doSomething() {
     }
} 

Now, checkFoo only works for Foo but does not work for Bar and vice-versa. How is the best 'design pattern' to structure this ? Should we add checks in each method and throw exceptions ? Is there a common solutions ?

Upvotes: 3

Views: 81

Answers (2)

Timothy Truckle
Timothy Truckle

Reputation: 15622

The "common solution" here is polymorphism.

In Java an enum is (almost) an ordinary class. Therfore it constants can implement interfaces like this:

interface Checkable{
  String doCheck();
}

class Plan {
     public enum Type implements Checkable{
         FOO{
            @Overide public String doheCheck() {
               return "result of Foo check";
            }
         }, BAR{
            @Overide public String doheCheck() {
               return "result of Bar check";
            }
         };
     }

     String check() {
          for(Checkable checkable: Type.values()){
              checkable.doCheck();
     } 


      String doSomething() {
     }
} 

In any way your callers should not have to deal with the fact that there are different Types to check...

Upvotes: 4

Eugene
Eugene

Reputation: 120968

If I understood this correctly you could create your enum a bit different:

enum Type {

    FOO {
        public  String getMe(){
            return "FOO";
        }    
    };

    // force every instance to implement this
    public abstract String getMe();
}

Upvotes: 3

Related Questions