什么是两个初始化之间的差异:这两个初始化有什么区别:Object x = new String(); String x = new String();
Object x = new String();
String x = new String();
在Java
谢谢!
什么是两个初始化之间的差异:这两个初始化有什么区别:Object x = new String(); String x = new String();
Object x = new String();
String x = new String();
在Java
谢谢!
Object x = new String(); // pointing to a String and saying - Hey, Look there! Its an Object
String x = new String();// pointing to a String and saying - Hey, Look there! Its a String
更重要的是: 可以访问字符串的方法取决于参考。例如:
public static void main(String[] args) {
Object o = new String();
String s = new String();
o.split("\\."); // compile time error
s.split("\\."); // works fine
}
+1详情/示例:) – async
有一个在初始化没有区别,只是在声明,因此在你的代码的其余部分将这两个变量类型的方式。
两者都是一样的,X会引用字符串对象。
但是Object x = new String();
中的x变量需要被类型转换为字符串,使用x.toString()
或(String)x
才能使用它。
不同之处在于第一个选项x
将被编译器视为Object,第二个选项将被视为String。例如:
public static void main (String[] args) throws Exception {
Object x = new String();
test(x);
String y = new String();
test(y);
// and you can also "trick" the compiler by doing
test((String)x);
test((Object)y);
}
public static void test(String s) {
System.out.println("in string");
}
public static void test(Object o) {
System.out.println("in object");
}
会打印:
in object
in string
in string
in object
Object x = new String();
这里,x
只有到Object
的方法和成员访问。 (要使用String
的成员,你必须强制转换的x
到String
(使用Downcasting in Java))
String x = new String();
这里,x
访问所有的方法和Object
以及String
成员。
正如其他answerers所指出的,这两种情况都会导致变量x持有对String的引用。唯一的区别是后续代码将如何看到引用:作为Object vs String,即确定编译器允许引用哪些操作。基本上,这个问题突出了静态类型语言(例如Java)和动态类型(例如Python,Javascript等)之间的差异。在后者,你不必声明引用的类型,所以这个代码仅仅是这样的:
var x = new String();
在这种情况下,编译器推断在运行的类型,但你输了一些静态类型检查编译时间。
在日常的Java代码,你将永远使用形式:
String x = new String();
因为这可以让你把X像一个字符串,并调用,例如方法toUpperCase()
就可以了。如果x是Object
,编译器将不允许你调用该方法,只有Object方法,例如equals()
。
然而,事实正好相反。在下面的情况:
List list = new ArrayList();
ArrayList list = new ArrayList();
除非您特别希望使用的ArrayList(不太可能)公开的方法,它始终是更好申报list
作为List
,不ArrayList
,因为这将允许您稍后将实现更改为另一种类型的列表,而无需更改调用代码。
区别是你需要投它很多 但是你可以使用相同的变量并用另一种类型重新初始化它。当你不断变化的变量时,是非常有用的..
例子:
Object x = new String();
if(x instanceof String){
System.out.println("String");
}
x = new ArrayList<String>();
if(x instanceof ArrayList){
System.out.println("ArrayList");
}
回报:
字符串 的ArrayList
的'Object'不是'String' .. 。 –