Java继承场景下各学院子类独立统计学生数与积分方案咨询
在每个子类单独声明static修饰的students和points不是最优解决方案,这种方案会导致严重的代码冗余:父类的AddPoints、Welcome等方法无法复用已定义的成员变量,你需要在每个子类中重复实现相同逻辑,完全违背了继承的代码复用设计初衷。
问题根源
你之前把父类的students和points设为static出现累加,是因为static修饰的变量属于类本身,所有该类的实例、子类实例都会共享同一份变量值,自然会出现跨学院数据混淆的问题。
两种更合理的实现方案
方案1:直接使用普通实例变量,将四个学院作为Houses类的独立实例(最简洁,优先推荐)
你不需要额外定义4个子类,四个学院本质就是属性值不同的Houses类对象,students和points用普通实例变量,每个实例自带独立的统计值,天然互不影响,代码可以简化为:
public class Houses { // 所有属性都是实例变量,每个实例自带独立值 int students; String color; String logo; String founder; String trait; String name; int points = 0; // 构造方法直接传入各学院的差异化属性 public Houses(String name, int students, String color, String logo, String founder, String trait) { this.name = name; this.students = students; this.color = color; this.logo = logo; this.founder = founder; this.trait = trait; welcome(); } protected void welcome() { System.out.println("Welcome to " + name + "! \n This house was founded by " + founder + " and his core value is " + trait + " , the house logo is " + logo + " and his color is " + color + "\n We have right now " + students + " students and " + points + " points. BEST OF LUCK!"); } public void addPoints(int x){ points += x; System.out.println(x + " Points added!\nYour house now have " + points + " points"); } public static void main(String[] args) { // 直接初始化四个学院实例即可,各自统计值完全独立 Houses gryffindor = new Houses("Gryffindor", 76, "Red", "Lion", "Godric Gryffindor", "Brave"); Houses slytherin = new Houses("Slytherin", 75, "Green", "Snake", "Salazar Slytherin", "Cunning"); // 调用加分方法只会影响当前实例的积分 gryffindor.addPoints(10); // 仅格兰芬多加10分,和其他学院无关 } }
方案2:必须保留子类继承结构时,用单例模式约束每个子类只有一个实例
如果你有明确需求要为不同学院实现差异化的自定义方法、必须用子类,那不需要修改为static变量,只要保证每个子类全局只有一个实例即可:
// 父类保持普通实例变量即可 public abstract class Houses { int students = 75; String color; String logo; String founder; String trait; String name; int points = 0; protected void welcome() { System.out.println("Welcome to " + name + "! \n This house was founded by " + founder + " and his core value is " + trait + " , the house logo is " + logo + " and his color is " + color + "\n We have right now " + students + " students and " + points + " points. BEST OF LUCK!"); } public void addPoints(int x){ points += x; System.out.println(x + " Points added!\nYour house now have " + points + " points"); } } // 格兰芬多子类设为单例,全局只有一个实例,统计值自然唯一 public class Gryffindor extends Houses { // 全局唯一实例 public static final Gryffindor INSTANCE = new Gryffindor(); // 构造方法私有,禁止外部新建实例避免统计混乱 private Gryffindor() { name = "Gryffindor"; students += 1; color = "Red"; logo = "Lion"; founder = "Godric Gryffindor"; trait = "Brave"; welcome(); } }
使用时直接调用单例即可:
Gryffindor gryffindor = Gryffindor.INSTANCE; gryffindor.addPoints(10);
内容的提问来源于stack exchange,提问作者lupintail
相关产品推荐
相关产品推荐

