java在为子类创建对象时,如何从hashMap实现属性?
我试图做的基本上是迭代我的类型,并使用我的hashMap作为查找表,然后在创建对象时选择类型。我不知道下一步需要做什么,因为当我已经有了一个新的构造函数时,它总是给我关于创建新构造函数的错误
import java.util.HashMap;
import java.util.Scanner;
public class disc {
private String title;
private String releaseDate;
HashMap<Integer, String> genre = new HashMap<Integer, String>();
Scanner mainInput = new Scanner(System.in);
public disc(String releaseDate, String title, HashMap<Integer, String> genre) {
this.title = title;
this.releaseDate = releaseDate;
this.genre = genre;
this.genre.put(1, "Horror");
this.genre.put(2, "Action");
this.genre.put(3, "Hip-Hop");
this.genre.put(4, "Pop");
this.genre.put(5, "Jazz");
this.genre.put(6, "Thriller");
}
子类:
import java.util.HashMap;
public class game extends disc{
private int PEGIRating;
private String Platform;
public game(int PEGIRating, String Platform, String title, String releaseDate, HashMap<Integer, String> genre){
super(releaseDate, title, genre);
this.PEGIRating = PEGIRating;
this.Platform = Platform;
game g = new game(18,"PS5","Evil Within","Feb 2018",1);
}
}
# 1 楼答案
如上所述,您正在game Constructor中初始化游戏对象,这将编译,但可能会导致运行时问题
为此,您将int数据类型传递到game构造函数的最后一个参数中,而不是传递HashMap<;整数,字符串>;正如您在构造函数签名中指定的那样。创建一个构造函数,该构造函数接受确切的参数列表,但最后一个数据类型为int,或者传递一个HashMap作为最后一个参数
# 2 楼答案
您正在尝试初始化game()构造函数中的游戏对象