Cast对象是克隆对象,还是Java中的引用?

问题描述 投票:0回答:1

我目前正在开发一个Java游戏,我将整个游戏保存为一个数组以便渲染它,因此,我注意到,当我设置时,有时对象似乎与其他对象纠缠在一起他们平等。虽然经过一些研究,我得出的结论是,我只是在创建一个对同一个对象的新引用。我已经尝试了各种方法来避免这个问题并且相当成功。但是我沿途尝试的其中一个tequince,只是将对象转换为另一种类型,作为一个粗略的例子:

 public class Apple {

     boolean TasteLikaAnApple;

     public Apple {
        TasteLikeAnApple = true;
     }
     public ChangeTaste (boolean newTaste) {
        TasteLikeAnApple = newTaste;      
     }   
 }

 public class Pear{

     boolean TasteLikaAnApple;

     public Apple {
        TasteLikeAnApple = false;
     }
     public ChangeTaste (boolean newTaste) {
        TasteLikeAnApple = newTaste;      
     } 
 }
 public class main {
     public static void main (String[] args) {

         Apple fruit1 = new Apple();
         Pear fruit2 = new Pear();

         fruit2 = (Pear) fruit1;

         fruit2.ChangeTaste(false);
     }
 }

现在,我不知道我是否可以把梨送到苹果公司,但上面的代码应该让你大致了解我的想法:

cast会创建一个新对象还是只是另一个引用?

或者在给定代码的上下文中,fruit1也将其字段TasteLikeAnApple设置为false?

java object casting
1个回答
0
投票

“铸造会创建一个新对象,还是仅仅是另一个参考?”

没有人。转换允许从类型分配到兼容类型(相同的层次结构)。

因此,从Apple到Pear的演员阵容没有任何意义,因为Apple和Pear不会成为同一层次结构的一部分,更具体地来说,这里(向下转发)Apple不是Pear的子类:

 Apple fruit1 = new Apple();
 Pear fruit2 = new Pear();

 fruit2 = (Pear) fruit1;

假设一个Fruit类及其两个子类:Apple和Pear。 你可以这样做这些垂头丧气:

 Fruit appleFruit = new Apple();
 Fruit pearFruit = new Pear();

 Pear pear = (Pear) pearFruit;
 Apple apple = (Apple) appleFruit;

或者这个向上:

Apple apple = new Apple();
Fruit appleFruit = apple;
© www.soinside.com 2019 - 2024. All rights reserved.