创建类中的非法自我引用



我是Java的新手,我的代码在Charmander/Squirtle/Bulbasaur.moveList的下面几行中给了我错误"非法自我引用">

static Pokemon Charmander = new Pokemon("Fire", "Charmander", 25, Charmander.moveList);
static Pokemon Squirtle = new Pokemon("Water", "Squirtle", 25, Squirtle.moveList);
static Pokemon Bulbasaur = new Pokemon("Grass", "Bulbasaur ", 25, Bulbasaur.moveList);

这是我的代码

public class Pokemon_Builder {
public static void main(String[] args) {
Move_Builder mb = new Move_Builder();
Charmander.moveList.add(mb.Ember);
Charmander.moveList.add(mb.Scratch);
Charmander.moveList.add(mb.Willowisp);
Charmander.moveList.add(mb.Recover);
Squirtle.moveList.add(mb.Bubble);
Squirtle.moveList.add(mb.Tackle);
Squirtle.moveList.add(mb.Powdersnow);
Squirtle.moveList.add(mb.Recover);
Bulbasaur.moveList.add(mb.Vinewhip);
Bulbasaur.moveList.add(mb.Poisonpowder);
Bulbasaur.moveList.add(mb.Tackle);
Bulbasaur.moveList.add(mb.Recover);
System.out.println(Charmander.moveList.size());
}
static Pokemon Charmander = new Pokemon("Fire", "Charmander", 25, Charmander.moveList);
static Pokemon Squirtle = new Pokemon("Water", "Squirtle", 25, Squirtle.moveList);
static Pokemon Bulbasaur = new Pokemon("Grass", "Bulbasaur ", 25, Bulbasaur.moveList);
}

这是口袋妖怪类的代码:

import java.util.LinkedList;
import java.util.List;
public class Pokemon{
String type;
String name;
int health;
List<Move> moveList = new LinkedList<Move>();
public Pokemon(String type, String name, int health, LinkedList moveList) {
this.type = type;
this.name = name;
this.health = health;
this.moveList = moveList;
}
public void getInfo (){
System.out.println("Pokemon Name "+ this.name);
System.out.println("Your Pokemon's type "+ this.type);
System.out.println("Your Pokemon's health "+ this.health);
}
public void addMove(Move toAdd){
if (moveList.size() < 5){
moveList.add(toAdd);
}
else{System.out.println("Can't learn any more moves!");
}
}
}

提前感谢您的帮助

在你的类Pokemon_builder中,你创建了 3 个口袋妖怪,在创建这些口袋妖怪时,你提供了一个 moveList。这些移动列表是在创建口袋妖怪时创建的。这意味着您现在尝试做的是将口袋妖怪的一个字段传递给该口袋妖怪的构造函数。

当您的口袋妖怪对象实例化自身时,静态成员对象创建会在构造函数之前运行。您正在尝试创建一个名为 Charmander 的对象,并将对 Charmander 中静态"movelist"对象的引用传递给 Charmander 的构造函数。您是在 Charmander 完成其对象实例化过程之前执行此操作的。因此,您正在尝试创建一个对象,该对象需要自身内部的引用来"构造"自身。

最新更新