Search code examples
javalogic

Implementing a three-valued logic operation with Boolean operators?


I've created an enum class Proposition with three possible constants,

public enum Proposition {

    TRUE, FALSE, NULL;

} 

and I'd like to make it so that, when I write code using Boolean operators

Proposition propA = Proposition.FALSE;

Proposition propB = Proposition.NULL;

Proposition propC = propA && propB;

propC would become NULL, following Kleene's logic. https://en.wikipedia.org/wiki/Three-valued_logic

How would I implement that in Java? Do I HAVE to use a method or can I use Boolean operators?


Solution

  • You can implement this yourself using enum methods (something like what we get from Predicate); operators can't be overridden in Java. Here's an example:

    enum Proposition {
        TRUE(Boolean.TRUE),
        FALSE(Boolean.FALSE),
        NULL(null) {
            @Override
            public Proposition and(Proposition other) {
                return this;
            }
    
            @Override
            public Proposition or(Proposition other) {
                return this;
            }
        };
    
        private final Boolean value;
        Proposition(Boolean value) {
            this.value = value;
        }
    
        public Proposition and(Proposition other) {
            if (NULL == other) return NULL;
            return of(this.value && other.value);
        }
        public Proposition or(Proposition other) {
            if (NULL == other) return NULL;
            return of(this.value || other.value);
        }
    
        public static Proposition of(Boolean bool) {
            return null == bool ? NULL : (bool ? TRUE : FALSE);
        }
    }
    

    And here's the call corresponding to your example:

    Proposition propA = Proposition.FALSE;
    Proposition propB = Proposition.NULL;
    
    Proposition propC = propA.and(propB);
    System.out.println(propC); // NULL
    

    In other words, call .or() method for || and .and() method for &&.