编写OfficeChair类。
- 有两个实例变量
- 有一个静态int,用于跟踪OfficeChairs的数量
- 有一个默认构造函数
- 有一个重载的构造函数 - 两个数据成员都作为输入
- 两个构造函数都需要添加到static int
编写两行代码,演示如何创建OfficeChair的实例 - 一个使用默认构造函数,另一个使用重载的构造函数。
您无需编写任何getter / setter。
我需要知道如何编写两行代码来创建实例。
public class OfficeChair
{
public string function chairSwivel;
private int chairSoftness;
static int chairCount = 0;
}
OfficeChair()
{
chairSwivel = “Yes”;
chairSoftness = “Not Given”;
chairCount = “Not Given”;
}
public OfficeChair( string Str, int num1, static int num2)
{
chairSwivel = str
chairSoftness = num1
chairCount = num2
}
}
public Class officeChairs {
public static void main(String args[])
{
Chair officeChair = new OfficeChair(Yes, Very Soft, 8)
答案 0 :(得分:3)
public class OfficeChair
{
// `string` is not a type in Java
// `function` is a made up keyword
// chairSwivel should probably be a `boolean` typed variable
public string function chairSwivel;
private int chairSoftness;
static int chairCount = 0;
} // Class definition ends
// This is outside the class, see above }
OfficeChair()
{
// Wrong quotes (for other literals as well)
chairSwivel = “Yes”;
// Type error - a string cannot be assigned to an integer variable.
chairSoftness = “Not Given”;
// Type error as per above, also fails to meet requirements
chairCount = “Not Given”;
}
// Please choose meaningful parameter/variable names
public OfficeChair( string Str, int num1, static int num2)
{
// Missing semicolons
chairSwivel = str
chairSoftness = num1
// Fails to meet requirements
chairCount = num2
}
} // Bogus, see first class-ending }
// Class should be `class` - all keywords in Java are lowercase.
// officeChairs is also mis-cased as class names should all be CamelCased.
// Only one class with a given name (or parent type if nested) can exist.
public Class officeChairs {
public static void main(String args[])
{
// There is no Chair type defined
// There is no Yes identifier in scope, string literals need quotes.
// Very Soft (or even the less-incorrect "Very Soft") is still not
// assignable to an integer. Missing semicolon.
Chair officeChair = new OfficeChair(Yes, Very Soft, 8)
在完成所有这些(可能不是全部)之后,使用new
creates a new instance:
new
运算符通过为新对象分配内存并返回对该内存的引用来实例化一个类。 new运算符还调用对象构造函数。
答案 1 :(得分:1)
那将是
OfficeChair officeChair1=new OfficeChair();
和
OfficeChair officeChair2=new OfficeChair("yes","verySoft",8);