gpt4 book ai didi

java - 使用辅助类引用创建的对象

转载 作者:行者123 更新时间:2023-12-01 17:00:08 25 4
gpt4 key购买 nike

祝大家一月快乐,

最近我一直在从头开始学习Java。这真的很有趣。我已经开始创建一个基本的角色扮演游戏,用户可以在其中进行选择和属性以及用户想成为战士还是法师。美好时光。

在我的主类中,我现在有了这个新的英雄对象,它存储了用户所需属性的输入以及他们是否想成为战士或法师。现在我想创建其他类来引用带有存储变量的新创建的对象。我完全迷路了。

因为我不想粘贴大量令人尴尬的蹩脚代码,所以我只使用一个非常简单的示例:

这是第一类,用户告诉我们他的英雄有多少力量:

import java.util.Scanner;

public class HeroCreation
{
int strength;
Scanner input = new Scanner(System.in);

public void setStr()
{
System.out.println("Please tell stackoverflow how much strength you want: ");
strength = input.nextInt();
System.out.println("Your strength is: " + strength + "!");
}

}

这是运行此方法的主类:

public class MainClass
{
public static void main(String args[])
{
HeroCreation hero1 = new HeroCreation();
hero1.setStr();

//Here is where I want to reference another class that refers to this new hero...

}
}

这就是我被困住的地方。我有这个新英雄了。该英雄的力量为10。我如何在其他辅助类中引用该英雄?从概念上讲,我的想法是错误的吗?

感谢您的时间和专业知识!

最佳答案

兄弟,你甚至还没有英雄,你拥有的只是一个HeroCreation

为您提供一些基本的面向对象分析和设计概念:

  • 作为起始设计规则,您应该为问题空间中的每个名词创建一个类,或者至少创建一个变量,并且应该为问题空间中的每个动词创建一个方法。

  • 在编写新代码时,您首先应该想到的是“哪个类负责这个”?将责任委托(delegate)给正确的类对于保持代码易于理解和扩展非常重要。通常,新职责不属于任何现有类,因此您必须添加新类。

利用这两条规则,这是我如何编写迄今为止的代码的起始版本。

Hero.java

public class Hero
{
private int strength;
private int intelligence;
// other attributes

public int getStrength() {
return this.strength;
}

public void setStrength(int strength) {
this.strength = strength;
}

public int getIntelligence() {
return this.intelligence;
}

public void setIntelligence(int intelligence) {
this.intelligence = intelligence;
}

// other "accessor" (get and set) methods for attributes
}

HeroCreation.java

import java.util.Scanner;

public class HeroCreation
{
Scanner input = new Scanner(System.in);

public int askStrength() {
return askIntegerAttribute("strength");
}

public int askIntelligence() {
return askIntegerAttribute("intelligence");
}

// ask other attribute values

private int askIntegerAttribute(String attribute) {
System.out.println("How much " + attribute + " do you want? ");
int value = input.nextInt();
System.out.println("Your " + attribute + " is: " + value + "!");
return value;
}
}

Main.java

public class Main
{
public static void main(String args[])
{
HeroCreation creation = new HeroCreation();

Hero hero1 = new Hero();
hero1.setStrength(creation.askStrength());
hero1.setIntelligence(creation.askIntelligence());

Hero hero2 = new Hero();
hero2.setStrength(creation.askStrength());
hero2.setIntelligence(creation.askIntelligence());

}
}

现在,您将继续向这些类添加符合其定义职责的变量和方法。您将继续为您遇到的其他职责创建其他类。

关于java - 使用辅助类引用创建的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28219523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com