简体   繁体   English

在 Java 8 中,我可以使用什么数据类型来代替“var”?

[英]What data type can I use instead of 'var' in Java 8?

var x = new something();

I tried to make that but Eclipse says我试图做到这一点,但 Eclipse 说

var cannot be resolved to a type var 无法解析为类型

What type can I use in Java 8?我可以在 Java 8 中使用什么类型?

Both of the following should work:以下两项都应该有效:

  • Something x = new Something();
  • Object x = new Something();

In addition to Something and Object , you should be able to use any class that Something extends from, or any interface that Something implements (either directly or indirectly).除了SomethingObject ,您应该能够使用Something扩展自的任何类,或者Something实现的任何接口(直接或间接)。


Probably a good idea to start reading up on how the Java type system works.开始阅读 Java 类型系统的工作原理可能是个好主意。

The var keyword was added in Java 10, and tells the compiler to infer the type from the value on the right side of the = assignment operator. var关键字是在 Java 10 中添加的,它告诉编译器从=赋值运算符右侧的值推断类型。

Which means that the following are equivalent, ie the compiler will generate the exact same bytecode:这意味着以下内容是等效的,即编译器将生成完全相同的字节码:

var x = new something();

something x = new something();

FYI: something is a type (class, interface, enum), and Java naming convention is for type names to start with uppercase letter, so it should be named Something .仅供参考: something是一种类型(类、接口、枚举),Java 命名约定是类型名称以大写字母开头,因此它应该命名为Something

    **Without var**
    String str = "Chaman Bharti";
    String substring = str.substring(7);
    System.out.println(substring);//Bharti
    System.out.println(substring.getClass().getTypeName());//java.lang.String

var is used to reduce boiler code in above line I have used String RHS(Right Hand Side) two times whereas in below line I have not used because Compiler infer according to assigned value of LHS(Left Hand Side). var 用于减少上面一行中的锅炉代码,我使用了 String RHS(Right Hand Side) 两次,而在下面一行我没有使用,因为编译器根据 LHS(Left Hand Side) 的分配值进行推断。

    **With var**
    var str = "Chaman Bharti";
    var substring = str.substring(7);
    System.out.println(substring);//Bharti
    System.out.println(substring.getClass().getTypeName());//java.lang.String

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

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