簡體   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