【发布时间】:2021-12-27 20:15:16
【问题描述】:
干杯,我对 java 很陌生,我和我遇到了一个问题 我有三个类,它们都继承了它们之间的东西。开始我有一个 A 类:
public class A{
private int index;
public A(int index) {
System.out.println("Creating an instance of A");
this.index = index;
}
}
然后我有一个 A 的子类,M 类,里面有一个枚举:
public class M extends A{
public enum Letter {
A,B,C;
}
private Letter letter;
public M(int index, Letter aLetter) {
super(index);
System.out.println("Creating an instance of M");
this.letter = aLetter;
}
}
最后是最后一个类 P,M 的子类:
public class P extends M {
private T t;
public enum T{
o,
a,
t
}
public P(int index, Letter aLetter, T aT) {
super(index,aLetter);
System.out.println("Creating an instance of P");
this.t = aT;
}
}
我想做的是创建例如P 类的 3 个对象,并将每个枚举的值随机传递给它们。我想在主类中创建一个函数,类似于:
Letter getRandLetter() {
Random rand = new Rand();
int pick = rand.nextInt(M.Letter.values().length);
if (pick == 0) {
return Letter.A;
} else if (pick == 1) {
return Letter.B;
} else {
return Letter.C;
}
}
我的主要看起来像这样:
int N = 3;
M[] new_m = new M[N]
for(int i = 0; i < N; i++) {
new_m[i] = new P(i, getRandLetter(), getRandT());
}
但是我收到此错误:Cannot make a static reference to the non-static method 。我可以做些什么来实现我想要的?
【问题讨论】:
标签: java parameters static parameter-passing