【问题标题】:Java: Modifying an object (declared in Class A, instanced in Class B) in Class CJava:在 C 类中修改对象(在 A 类中声明,在 B 类中实例化)
【发布时间】:2014-07-06 02:42:19
【问题描述】:

我正在编写一个小游戏,游戏的一部分是在已经存在的宠物界面上添加商店界面。 我选择了一只猫。 Cat 类包含 Cat 对象构造函数。

    public Cat(String aName, Gender aGender ,String aTrait,String aAgeEffect,int aWeight, int aPetDay, int aPetMonth, int aPetYear, String aWhiskerLength, String aFurColour, String aEyeColour){   
    super(aName, aGender , aTrait,  aWeight,  aAgeEffect, aPetDay, aPetMonth, aPetYear);
    petDay = aPetDay;
    petMonth = aPetMonth;
    petYear = aPetYear;
    whiskerLength = aWhiskerLength;
    furColour = aFurColour;
    eyeColour = aEyeColour;
    penaltyPoints = 0;
        }

然后,Cat_Interface 类使用用户输入设置 Cat 的实例。

public Cat_Interface() {
        final Cat cat = new Cat(name, null, trait, null, 50, day, month, year, null, fur, eye);
}

(名称等变量是我用来传递用户输入的临时变量。Cat 对象确实有效。我已经测试了很多次,所有值都正确传递。)

当我创建 PetShopInterface 类 + 尝试使用在 Cat_Interface 类 ( cat ) 中创建的对象时,我的问题开始出现。

例如,当我设置了商店的界面时,我会尝试这样做:

public void buyBed() {
System.out.println(Cat_Interface.cat.getName());
}

只是看看会发生什么。我得到一个指向这段代码的空指针。 这不应该发生,因为我首先运行 Cat_Interface 类,设置新 Cat,然后启动商店界面。

任何帮助将不胜感激。

【问题讨论】:

  • 当您在 SO 中发帖时,请尝试使您的格式更好。具体来说,是 4 个空格而不是制表符。
  • 所有你需要的是一个对象的引用,以便修改它(如果它是可变的)。但是没有那个参考你就做不到。并且仅仅拥有一个具有相同类类型的引用变量并不像拥有实际引用。
  • 顺便说一句,你不应该使用“接口”作为你的类名的一部分。 “接口”在 Java 中具有不同的含义(这不是它)。
  • 我们被告知对于这个游戏,我们必须调用 Cat、Cat_Interface 等类。我知道这是不好的做法,但我只是按照我被告知的做 :) 通过“参考”做你的意思是这样的: public Cat_Interface myInterface;在其他班级?
  • “引用”是指存储在类似Cat_inteface myInterface 中的,它实际上解决了您要操作的对象(而不是NULL 而不是 Cat_Interface 的其他实例)。仅仅拥有一个类型的变量是没有引用的。

标签: java class object interface


【解决方案1】:
public Cat_Interface() {
    final Cat cat = new Cat(...);
}

这会在构造函数的范围内创建一个新的猫。你想要这样的东西:

public final Cat cat;

public Cat_Interface() {
    cat = new Cat(...);
}

然后你需要实例化它:

Cat_Interface ci = new CatInterface();
System.out.println(ci.cat.getName());

【讨论】:

  • 我已经按照你说的做了修改。但是,Cat_Interface 的实例已在另一个类(测试器)中声明,我无法在 PetShopInterface 类中引用该接口的实例,而无需仍然执行 Cat_Interface.cat.getname()
  • 它应该是静态的吗?
猜你喜欢
  • 1970-01-01
  • 2012-11-18
  • 2023-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多