-2

Can I make a class object treated as another data type? I want to make an class, that can be read as a boolean object, when the object is created in a main class. For example

public class ReturnValue {
    String one = "text";
    // some code that makes this class a boolean 'true'.
    }

public class main {
    public static void main(String[] args) {
        returnValue object = new returnValue();
        if object
            System.out.println("the subclass is true.");  //so that it could print out.
    }
}
belle park
  • 23
  • 5

2 Answers2

3

I think the only way is creating a method that will tell you if that object is "true" according to the properties:

public class returnValue {
    String one = "text";
    // some code that makes this class a boolean 'true'.
   public boolean isTrue() {
      return "text".equals(one); // just as example.
   }
}

public class main {
    public static void main(String[] args) {
        returnValue object = new returnValue();
        if (object.isTrue())
            System.out.println("the subclass is true.");  //so that it could print out.
    }
}
alayor
  • 4,537
  • 6
  • 27
  • 47
  • 1
    LOL! I literally ended my answer with *"...you might even call `getValue` `isTrue` or something..."* Then posted, and saw you'd used that very name above. :-) – T.J. Crowder Oct 25 '17 at 12:54
3

Java doesn't have the concept of automatically converting an object to a primitive value like a boolean (other than when the object is a Boolean, of course).

In your example, Boolean would be a reasonable choice (if it has to be an object type):

public static void main(String[] args) {
    Boolean object = Boolean.TRUE;
    if (object) {
        System.out.println("the subclass is true.");  //so that it could print out.
    }
}

If you wanted to roll your own, though, you'd have to provide an accessor method for the "boolean" value of the object:

class ReturnValue {
    private boolean value;

    ReturnValue(boolean v) {
        this.value = v;
    }

    public boolean getValue() {
        return this.value;
    }
}

then

public static void main(String[] args) {
    ReturnValue object = new ReturnValue(true);
    if (object.getValue()) {
        System.out.println("the subclass is true.");  //so that it could print out.
    }
}

You might even call getValue isTrue or similar.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I was hoping Java would provide converting an object to a primitive value. Thanks a lot anyway! – belle park Oct 25 '17 at 13:04
  • @bellepark: Only for the predefined classes with corresponding primitives (`Boolean` => `boolean`, `Long` => `long`, etc.), not our own classes. – T.J. Crowder Oct 25 '17 at 13:05