[英]Is it possible to make a new kind of variable that can be different things?
I want to make a new variable with which i can do the following: 我想创建一个新变量,我可以使用它来执行以下操作:
Variable v1 = 1;
Variable v2 = "Test";
Variable v3 = 7.31;
Is this possible, or is this impossible? 这可能,或者这是不可能的?
If you take advantage of auto-boxing (Java SE 5.0 and later) then every one of those can be stored in an Object
(ie the base class of all Java types): 如果你利用自动装箱(Java SE 5.0及更高版本),那么每一个都可以存储在一个
Object
(即所有Java类型的基类):
public class foo {
static public void main(String[] params) {
Object v1 = 1;
Object v2 = "Test";
Object v3 = 7.31;
System.out.println(v1 + " " + v1.getClass().getName());
System.out.println(v2 + " " + v2.getClass().getName());
System.out.println(v3 + " " + v3.getClass().getName());
}
}
output: 输出:
% java foo
1 java.lang.Integer
Test java.lang.String
7.31 java.lang.Double
This does not necessarily make it a good idea, though! 但这并不一定是个好主意!
The output shown above shows how although every variable was declared as an Object
, their real class name is one more appropriate for their type. 上面显示的输出显示了虽然每个变量都被声明为
Object
,但它们的真实类名称更适合它们的类型。 It's only because every class in Java is derived from Object
that the declarations can work that way. 这只是因为Java中的每个类都是从
Object
派生的,声明才能以这种方式工作。
It is possible. 有可能的。 Check the code below:
检查以下代码:
Object a;
Object b;
Object c;
a = 1;
b = "abc";
c = 1.72d;
or another way: 或另一种方式:
Object a;
a = 1;
a = "abc";
a = 1.72d;
In this case we observe autoboxing , when a value is wrapped to a suitable object type. 在这种情况下,当值被包装到合适的对象类型时,我们会观察到自动装箱 。
As Object
class is the parent for all java objects, then we have a way to code as I described above. 由于
Object
类是所有java对象的父类,因此我们可以像上面描述的那样编写代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.