使类对象成为java中的特定数据类型
是否可以将类对象视为另一种数据类型?我想创建一个类,当对象在主类中创建时,该类可以作为布尔对象读取。 比如说使类对象成为java中的特定数据类型,java,Java,是否可以将类对象视为另一种数据类型?我想创建一个类,当对象在主类中创建时,该类可以作为布尔对象读取。 比如说 public class ReturnValue { String one = "text"; // some code that makes this class a boolean 'true'. } public class main { public static void main(String[] args) { return
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.
}
}
我认为唯一的方法是创建一个方法,根据属性告诉您该对象是否为“真”:
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.
}
}
Java没有将对象自动转换为原始值(如
布尔值
)的概念(当然,当对象是布尔值
时除外)
在您的示例中,Boolean
将是一个合理的选择(如果它必须是对象类型):
但是,如果您想自己滚动,则必须为对象的“布尔”值提供一个访问器方法:
class ReturnValue {
private boolean value;
ReturnValue(boolean v) {
this.value = v;
}
public boolean getValue() {
return this.value;
}
}
然后
您甚至可以调用
getValue
isTrue
或类似功能。注意java命名约定。类名应该以大写字母开头。您是说要检查一个对象是否是另一个对象的子类吗?类是一种类型,是的。您的if
语句甚至不是有效的语法,尽管类型不是Boolean
的对象不能作为布尔对象计算。“//一些代码使这个类成为布尔值‘true’。”你是什么意思?哈哈!我的答案以“…你甚至可以调用getValue
isTrue
或其他东西…”。。。“然后发布,看到您在上面使用了这个名字::-)我希望Java能够提供将对象转换为原始值的功能。无论如何,非常感谢@bellepark:仅适用于具有相应原语的预定义类(Boolean
=>Boolean
,Long
=>Long
等),而不是我们自己的类。
class ReturnValue {
private boolean value;
ReturnValue(boolean v) {
this.value = v;
}
public boolean getValue() {
return this.value;
}
}
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.
}
}