我有一个要求我创建枚举类型的作业。我的问题是,在我初始化它们之后,如何将它们引入默认和参数化构造函数?我试过以下但它不起作用......任何想法?感谢
package magazine;
import paperPublication.PaperPublication;
public class Magazine extends PaperPublication {
private enum paperQuality {LOW, NORMAL, HIGH};
private enum issuingFrequency {WEEKLY, MONTHLY, YEARLY};
public Magazine() {
paperQuality = null; //doesn't work
issuingFrequency = null; //doesn't work
}
public Magazine (double price, int numberOfPages, enum paperQuality //doesn't work, enum issuingFrequency //doesn't work) {
}
}
答案 0 :(得分:6)
这是一个类型定义:
private enum paperQuality ...
但是你实际上没有声明该类型的字段。尝试这样的事情:
private enum PaperQuality {...};
private PaperQuality paperQuality;
第一行定义PaperQuality枚举,定义任何PaperQuality可以容纳的各种值。第二行创建一个名为paperQuality
的私有字段。构造函数可能如下所示:
public Magazine (double price, int numberOfPages, PaperQuality paperQuality) {
...
this.paperQuality = paperQuality;
}
答案 1 :(得分:4)
您已声明了类型,但未声明实例。你会想要......
public enum PaperQuality {LOW, NORMAL, HIGH};
public enum IssuingFrequency {WEEKLY, MONTHLY, YEARLY};
PaperQuality paperQuality;
IssuingFrequency issuingFrequency;
public Magazine() {
paperQuality = null;
issuingFrequency = null;
}
public Magazine (double price, int numberOfPages, PaperQuality paperQuality){
//logic here
}
我建议您阅读有关Java枚举的教程。
答案 2 :(得分:1)
enum
关键字与class
关键字类似:它定义了类型,而不是变量。
您的代码类似于以下内容:
public class Magazine extends PaperPublication {
private class paperQuality { /* something */ }; // note class instead of enum
private class issuingFrequency { /* something */ };
public Magazine() {
paperQuality = null; //doesn't work -- beacuse paperQuality is a class
paperQuality a; // does work because class name is suitable for variable definition
a = null; // you can assign null to class variables
答案 3 :(得分:0)
声明枚举类型的变量:
private paperQuality quality;
(enum paperQuality { ... }
只定义枚举类型,它不会创建变量!)。
此外,您无法将null
分配给枚举类型,它必须是枚举值之一(即LOW
)。
答案 4 :(得分:0)
例如,您可以在类
的主体中创建枚举enum Sex {
MALE,
FEMALE
}
此外,您可以创建一个单独的类。然后使用枚举类型声明变量,并在构造函数的括号中指定您创建的类型
private Sex enSex;
private String personName;
private int personAge;
private double personWeight;
public Person(String name, int age, double weight, Sex enSex) {
this.personName = name;
this.personAge = age;
this.personWeight = weight;
this.enSex = enSex;
}
答案 5 :(得分:0)
private enum paperQuality {LOW, NORMAL, HIGH};
private enum issuingFrequency {WEEKLY, MONTHLY, YEARLY};
首先为枚举类型创建一个变量。
paperQuality paperqual;
issuingFrequency issuingfre;
然后您可以使用这些枚举变量来分配值
public Magazine() {
paperqual= null;
issuingfre= null;
}
public Magazine (paperQuality pq,issuingFrequency isq) {
paperqual = pq;
issuingfre = isq;
}
答案 6 :(得分:-1)
枚举不是数据类型,更像是“class”关键字。示例中的数据类型为paperQuality和issuingFrequency。所以:
public Magazine (double price,
int numberOfPages,
paperQuality quality,
issuingFrequency freq) {
}