【问题标题】:Why would you create a class instance using (CustomClass) "string" in Java?为什么要在 Java 中使用 (CustomClass) "string" 创建一个类实例?
【发布时间】:2018-08-21 11:18:50
【问题描述】:

我是 Java 新手,正在从事一个现有的大型项目。有几次,我遇到了这样的代码:variable = (CustomClass) "string";。 现在,我真的不明白你为什么要这样做,以及它与variable = new CustomClass("string"); 有何不同。 CustomClass 有一个带有一个字符串参数的构造函数。
在某些情况下,上面的代码不起作用,这就是我遇到它的原因。但首先,我想了解它的作用,而谷歌似乎没有帮助。或者很可能我只是还不知道如何准确地表达这个问题????

【问题讨论】:

  • 您遇到的代码似乎试图将字符串文字转换为CustomClass。这对我来说很可疑,因为String 是一个最终类,不能扩展,所以我怀疑这个类可以用来转换字符串。
  • 您不能将String 转换为CustomClass 并且仍然可以编译代码。

标签: java class constructor type-conversion instance


【解决方案1】:

variable = (CustomClass) another_variable_reference;

上面这行代码会告诉JVManother_variable_reference是-variable引用类的类类型,这里是CustomClass。因此,将 another_variable_reference 指向的引用分配给引用 variable

variable = new CustomClass(another_variable_reference);

上面会新建一个CustomClass的Object,并将对象引用赋值给变量

因此,在第一种情况下,我们创建一个新的reference,它指向一个现有的对象,而在第二种情况下,我们创建一个新的Object 并将其引用分配给variable

【讨论】:

  • 终于找到我的问题了。 another_variable_reference 实际上是 jListCustomers.getSelectedValue(),我的 GUI 编辑器不知何故更改为输入 JList<String>。将类型更改为JList 即可解决。
猜你喜欢
  • 2021-03-23
  • 1970-01-01
  • 2018-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多