Java Flag Interfaces

What is a Java Flag Interface?

  • Sometimes completely empty interfaces serve as a marker that a class has a special property.
  • java.io.Serializeable interface existing in the Java API is a good example.
  • Classes that implement Serialize don't have to add any methods or variables.
  • java.io.Serializeable interface simply identifies that classes that implements that interface is able to be serialized.
    Example of Flag Interface:
    interface BeSlaughtered {}  // Flag interface
    interface Organic {
      boolean IsOrganic();
    }
    class Car implements  Organic {
      // Implemented method from the interface Organic:
      @Override
      public boolean IsOrganic() { 
        return false;
      }
    }
    // all objects of Bull can be slaughtered
    class Bull implements Organic, BeSlaughtered {
      // Implemented method from the interface Organic:
      @Override
      public boolean IsOrganic() {
        return true;
      }
    }
    public class Reporter {
      public void executeReport(Organic obj) {
        System.out.println("The fact that objects of "
        + obj.getClass().getSimpleName() + " is Organic is " + obj.IsOrganic());
        String stateText=" NOT";
        if (obj instanceof BeSlaughtered) {
          stateText="";
        }
        System.out.println("Objects of "
          + obj.getClass().getSimpleName() + " can"+stateText+" be slaughtered.");
      }
      public static void main(String[] args) {
        Reporter rep= new Reporter();
        rep.executeReport(new Car());
        rep.executeReport(new Bull());
      }
    }
    
    The result of this is:
    The fact that objects of Car is Organic is false
    Objects of Car can NOT be slaughtered.
    The fact that objects of Bull is Organic is true
    Objects of Bull can be slaughtered.
    You can download this example here (needed tools can be found in the right menu on this page).
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.