我正在玩java并且正在逐步学习。为了不写我的整个人生故事,它来了。
我正在制作带有一些统计数据,玩家,敌人等的文字游戏。为此我正在使用课程。最近,我来到了#34;延伸"功能,我正在尝试实现它。我创造了一个阶级角色,延伸到玩家和敌人。当我执行代码时,似乎它不会继承任何东西。非常感谢任何建议。谢谢!
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());
}
}
答案 0 :(得分:2)
此代码:
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;
}
}
答案 1 :(得分:1)
问题是你不是在基类中覆盖这些值,而是在继承中。
您应该在构造函数中初始化这些值。
示例:
public class Character {
int cc;
// ...
}
public class Player extends Character {
public Player() {
cc = 5;
// ...
}
}
你所做的是在基类中声明变量而不是初始化它们,并同时在同一个子类中声明变量。
更多阅读:https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html