【问题标题】:change object variable from another object's method从另一个对象的方法更改对象变量
【发布时间】:2018-08-23 11:26:40
【问题描述】:

这可能是非常新手,但我已经尝试了一段时间,但我无法找到答案。

package playground.space;

public class Fourlegs {
    String room;

    public static void main(String[] args) {
        Fourlegs program = new Fourlegs();

        program.start();
    }

    public void start() {
        Fourlegs cat = new Fourlegs();
        cat.room = "office";
        Fourlegs dog = new Fourlegs();
        dog.room = "office";

        //dog moves to the carpark, and the cat follows the dog
        dog.move("carpark");
    }

    public void move(String i) {
        this.room = i;

        //cat cannot be resolved to a variable
        cat.room = this.room; //the cat's room will be the same as the dog's room.
        System.out.println("the cat is in the " + cat.room);
    }
}

我收到错误:cat 无法解析为变量。(显然)。

如何通过其他方法操作“猫”?

【问题讨论】:

  • cat 在方法start() 中声明,这意味着它仅在该方法的范围内可用。将其声明为类属性(如room),您可以在该类的所有方法中使用它。
  • 为什么在dog 上调用move 也会影响cat
  • 了解一点 Java 中的对象引用可能会有所帮助。这是 StackOverflow 上的一篇文章,我对此进行了解释:Two newly created objects seem to refer to the same address.

标签: java object methods


【解决方案1】:

您正在尝试访问其范围之外的变量,变量 cart 仅存在于方法 start 中。
您必须将要处理的对象传递给此方法:

public void move(String i, Fourlegs fourleg) {
  fourleg.room = this.room
}

现在您可以在 Fourlegs 的任何实例上调用方法

编辑: 新方法:

public class Fourlegs {
    String room;

    public void move(String i) {
        this.room = i;
        //kind of unnecesary:)
        this.room = this.room;
    }
}


public class FourlegStorage {
 private List<Fourleg> fourlegs = new ArrayList<>();
    public void start() {
        Fourlegs cat = new Fourlegs();
        fourlegs.add(cat);
        cat.room = "office";
        Fourlegs dog = new Fourlegs();
        fourlegs.add(dog);
        dog.room = "office";

        //dog moves to the carpark, and the cat follows the dog
        dog.move("carpark");
    }

}

【讨论】:

  • 您的解决方案运行良好。谢谢!但是,我对修复范围更感兴趣,因为,如果我有另一个“四足”:“老虎”怎么办?例如。
  • 您将不得不为您的对象考虑一种存储方式,例如数组或列表。也许你可以改变类,所以类只代表一个 Fourleg。然后你可以在任何 Fourleg 实例上调用该方法移动并传递所需的字符串,并且你调用该方法的对象将执行该方法
  • 补充:那么您将需要另一个类来管理和维护您的 Fourleg 对象,因此您将拥有一个类 FourlegStorage,您可以在其中创建 Fourleg 对象并在其上调用方法
  • @JosephKwong 因此,您可以将带有 Tiger 的 FourLeg 引用传递给此方法。这个解决方案是正确的。
  • @JosephKwong 检查 deHaar 的答案以获取详细示例和对象的干净拆分。如果您只是对了解范围和类感兴趣,我的解决方案非常适合您。
【解决方案2】:

我认为这不是单门课就能解决的任务。从面向对象的角度来看(在 Java 中编程时应该这样做),您至少需要 3 个类,它们是 LocationFourLeggedAnimal 和一个主类,比如说 FourLeggedMain

当动物被命名并在某个位置时,它应该看起来像这样:

package fourlegs;

public class FourLeggedAnimal {

    protected String name;
    protected Location location;

    public FourLeggedAnimal(String name, Location room) {
        this.name = name;
        this.location = room;
    }

    public Location getLocation() {
        return location;
    }

    public void follow(FourLeggedAnimal animal) {
        this.location = animal.getLocation();
    }

    public void moveTo(Location room) {
        this.location = room;
    }

    public String getCurrentLocation() {
        return location.getName();
    }
}

地点只需要一个名字:

package fourlegs;

public class Location {

    private String name;

    public Location(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

主要执行包含其他对象的逻辑:

package fourlegs;

public class FourLegsMain {

    public static void main(String[] args) {
        Location office = new Location("office");
        Location carpark = new Location("carpark");

        FourLeggedAnimal cat = new FourLeggedAnimal("cat", office);
        FourLeggedAnimal dog = new FourLeggedAnimal("dog", office);

        System.out.println("The cat is at the " + cat.getCurrentLocation());
        System.out.println("The dog is at the " + dog.getCurrentLocation());

        dog.moveTo(carpark);

        System.out.println("The dog went to the " + dog.getCurrentLocation());
        System.out.println("The cat is still at the " + cat.getCurrentLocation());

        cat.follow(dog);

        System.out.println("The cat followed the dog and is at the "
                + cat.getCurrentLocation()
                + " now");
    }
}

执行它将提供以下输出:

猫在办公室
狗在办公室
狗去了停车场
猫还在办公室
猫跟着狗,现在在停车场

【讨论】:

    【解决方案3】:

    您在start 方法中定义了对象cat,并在方法move 中使用它。

    当您在方法中定义变量时,它的范围仅限于该方法。要在同一个类中的不同方法中使用它,您应该在类级别定义变量并且错误应该消失。

    在类级别定义变量以解决错误

    package playground.space;
    
    public class Fourlegs {
    String room;
    Fourlegs cat; // global variable here
    
    public static void main(String[] args) {
        Fourlegs program = new Fourlegs();
    
        program.start();
    }
    
    public void start() {
        Fourlegs cat = new Fourlegs();
        cat.room = "office";
        Fourlegs dog = new Fourlegs();
        dog.room = "office";
        dog.cat = cat; // global variable set here
    
        //dog moves to the carpark, and the cat follows the dog
        dog.cat = new Fourlegs();
        dog.move("carpark");
    }
    
    public void move(String i) {
        this.room = i;
    
        cat.room = this.room; //the cat's room will be the same as the dog's room.
        System.out.println("the cat is in the " + cat.room);
    }
    
    
    }
    

    【讨论】:

    • 会不会像public Object cat;
    • 在你的情况下,它应该是Fourlegs cat = new Fourlegs();。如果您愿意,可以将其定义为 public,但我建议将其设为私有,并创建一个公共 getter 方法来访问该值
    • cat 作为FourLegs 中的一个字段从设计的角度来看没有多大意义(它会导致堆栈溢出,因为现在您正在递归地创建FourLegs 的实例) .
    • 您的编辑修复了堆栈溢出问题,但作为设计仍然没有意义(为什么FourLegs另一个FourLegs...)。 move不需要访问cat,只需要修改FourLegsroom字段即可。
    • 我同意。这只是试图解决 OP 面临的问题。
    【解决方案4】:

    我会这样做:

    package playground.space;
    
    public class Fourlegs {
    
        String room;
    
        public static void main(String[] args) {
            Fourlegs program = new Fourlegs();
    
            program.start();
        }
    
        public void start() {
            Fourlegs cat = new Fourlegs();
            cat.room = "office";
            Fourlegs dog = new Fourlegs();
            dog.room = "office";
    
            //dog moves to the carpark, and the cat follows the dog
            dog.move("carpark");
            cat.follow(dog);
            System.out.println("the cat is in the " + cat.room);
        }
    
        public void follow(Fourlegs other) {
            room = other.room;
        }
    
        public void move(String newRoom) {
            this.room = newRoom;
        }
    }
    

    我添加了一个方法follow 让每个Fourleg 跟随另一个Fourleg。也许这更面向对象。

    【讨论】:

    • 这怎么能接近回​​答手头的问题?
    【解决方案5】:

    这是我的尝试。我对发布的代码进行了一些更改:

    public class Fourlegs {
    
        String room;
        private String id; // to identify a dog, cat, etc.
    
        public static void main(String[] args) {
            Fourlegs program = new Fourlegs();
            program.start();
        }
    
        public void setId(String id) {
            this.id = id;
        }
        public String getId() {
            return this.id;
        }   
    
        public void start() {
            Fourlegs cat = new Fourlegs();
            cat.setId("Cat-Fluffy");
            cat.room = "office";
            Fourlegs dog = new Fourlegs();
            dog.setId("Dog-Toby");
            dog.room = "office";
            System.out.println(dog.getId() + " is in the " + dog.room);
            System.out.println(cat.getId() + " is in the " + cat.room);
            // dog moves to the carpark, and the cat follows the dog
            dog.move("carpark");
            // the cat's follows the dog.
            cat.move(dog.room);
        }
    
        public void move(String i) {
            this.room = i;
            System.out.println(this.getId() + " moved " + this.room);
        }
    }
    

    输出:

    Dog-Toby is in the office
    Cat-Fluffy is in the office
    Dog-Toby moved to carpark
    Cat-Fluffy moved to carpark
    

    【讨论】:

      猜你喜欢
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多