Java class 扩展无法正常工作

Java class extends not working properly

正在玩 java 并逐步学习。为了不写我的整个人生故事,它来了。

我正在制作一个包含一些统计数据、玩家、敌人等的文字游戏。为此,我使用 classes。最近,我遇到了 "extends" 函数并尝试实现它。我做了一个 class 角色,它延伸到玩家和敌人。当我执行代码时,它似乎不会继承任何东西。将不胜感激任何建议。谢谢!

P.S。可以使用哪些标签?

import java.util.Random;

public class Character
{
    Random rand = new Random();

    int cc;
    int strength;
    int life;

    //getters and setters
}

public class Player extends Character
{
    int cc = rand.nextInt(20)+51;
    int strength = rand.nextInt(3)+4;
    int life = rand.nextInt(5)+16;
}

public class Enemy extends Character
{
    int cc = rand.nextInt(10)+31;
    int strength = rand.nextInt(3)+1;
    int life = rand.nextInt(5)+6;
}

class myClass
{
    public static void main(String[] args)                                                       
    {
    Player argens = new Player();

    System.out.println("This is you:\n");
    System.out.println("Close Combat " + argens.getCC());
    System.out.println("Strength " + argens.getStrength());
    System.out.println("Life " + argens.getLife());


    Enemy kobold = new Enemy();

    fight (argens, kobold);

    fight (argens, kobold);
    }

    static void fight(Player p, Enemy e)
    {

        p.setLife(p.getLife() - e.getStrength());

System.out.println("\nRemaining life");

System.out.println(p.getLife());

System.out.println(e.getLife());

    }

}

此代码:

public class Player extends Character
{
    int cc = rand.nextInt(20)+51;
    int strength = rand.nextInt(3)+4;
    int life = rand.nextInt(5)+16;
}

不设置超类的字段。它在子类中声明和设置新字段,而不触及超类的字段。

要设置超类的字段,请创建 protected 并在子类的构造函数中设置它们:

public class Player extends Character
{
    public Player()
    {
        cc = rand.nextInt(20)+51;
        strength = rand.nextInt(3)+4;
        life = rand.nextInt(5)+16;
    }
}

问题是您不是在基 class 中覆盖这些值,而是在继承的

中覆盖这些值

您应该在构造函数中初始化这些值。

示例:

public class Character {
  int cc;
  // ...
}

public class Player extends Character {
  public Player() {
    cc = 5;
    // ...
  }
}

您所做的是在基 class 中声明变量而不是初始化它们并同时在子 class 中声明具有相同名称的变量。

更多阅读:https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html