繁体   English   中英

Java 类扩展无法正常工作

[英]Java class extends not working properly

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

我正在制作一个带有一些统计数据、玩家、敌人等的文本游戏。为此,我使用了类。 最近,我遇到了“扩展”功能并正在尝试实现它。 我制作了一个类角色,它扩展到玩家和敌人。 当我执行代码时,它似乎不会继承任何东西。 将不胜感激任何建议。 谢谢!

PS 哪些标签可以使用?

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;
    }
}

问题是您不是在基类中而是在继承中覆盖这些值。

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

例子:

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM