繁体   English   中英

两个初始化之间有什么区别:Object x = new String(); String x = new String();

[英]what's the difference between the two initialization: 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

更重要的是:可以访问的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将被编译器视为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 (使用Java中的Downcast ))

String x = new String();

在这里, x可以访问ObjectString所有方法和成员。

两者都相同,X将引用字符串对象。

但是Object x = new String(); x变量Object x = new String(); 在使用它之前,需要使用x.toString()(String)x将类型转换为String。

正如其他回答者所指出的,两种情况都会导致变量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 ,因为这样可以让您稍后将实现更改为另一种类型的List,而无需更改调用代码。

不同之处在于您需要多次使用它,但是您可以使用相同的变量并使用其他类型重新初始化它。 当您使用更改变量时,它非常有用。

例:

Object x = new String();
if(x instanceof String){
    System.out.println("String");
}
x = new ArrayList<String>();
if(x instanceof ArrayList){
    System.out.println("ArrayList");
}

收益:

String ArrayList

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM