Java 什么';s两个初始化之间的差异:Object x=new String();字符串x=新字符串();

Java 什么';s两个初始化之间的差异:Object x=new String();字符串x=新字符串();,java,Java,两种初始化之间的区别是什么: Object x = new String(); String x = new String(); 在爪哇 谢谢! 更重要的是: 可以访问的字符串方法取决于引用。例如: public static void main(String[] args) { Object o = new String(); String s = new String(); o.split("\\."); // compile time error s.s

两种初始化之间的区别是什么:

Object x = new String(); 
String x = new String();
在爪哇

谢谢!

更重要的是: 可以访问的字符串方法取决于引用。例如:

public static void main(String[] args) {
    Object o = new String();
    String s = new String();
    o.split("\\."); // compile time error
    s.split("\\."); // works fine

}

初始化没有区别,只是声明不同,因此代码的其余部分看到变量类型的方式也不同。

两者都相同,X将引用string对象


但是
Object x=new String()中的x变量x.toString()
(String)x
将代码>类型转换为字符串。

区别在于,在第一个选项中,编译器将
x
视为对象,在第二个选项中,它将被视为字符串。例如:

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
在这里,
x
只能访问
对象的方法和成员。
(要使用
String
成员,必须将
x
键入
String
(使用))


在这里,
x
可以访问
对象
以及
字符串
的所有方法和成员,正如其他回答者所指出的,这两种情况都会导致变量x包含对字符串的引用。唯一的区别是后续代码将如何看待引用:对象与字符串,即确定编译器将允许对引用执行哪些操作

本质上,这个问题强调了静态类型语言(如Java)和动态类型语言(如Python、Javascript等)之间的区别。在后者中,您不必声明引用的类型,因此其代码如下所示:

var x = new String();
在这种情况下,编译器会在运行时推断类型,但会在编译时丢失一些静态类型检查

在日常Java代码中,您将始终使用以下形式:

String x = new String();
因为这将允许您将x视为字符串并调用,例如,方法
toUpperCase()
。如果x是
对象
,编译器将不允许您调用该方法,只允许调用对象方法,例如
equals()

但是,在以下情况下,情况正好相反:

List list = new ArrayList();
ArrayList list = new ArrayList();

除非您特别希望使用ArrayList公开的方法(不太可能),否则最好将
列表
声明为
列表
,而不是
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");
}
Object x=新字符串();
if(字符串的x实例){
System.out.println(“字符串”);
}
x=新的ArrayList();
if(ArrayList的x实例){
System.out.println(“ArrayList”);
}
返回:


ArrayList

一个
对象
不是一个
字符串
。。。
String x = new String();
List list = new ArrayList();
ArrayList list = new 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");
}