我有一个关于类和对象的作业。类是电视,电视对象会有属性,其中一些属性是常量
·制造商。制造商属性将保存品牌名称。一旦创建了电视,这一点就不能更改,因此命名常量也是如此。
·screenSize。screenSize属性将保存电视屏幕的大小。这是不能改变的
我不确定我对常量字段的声明,我不能理解它们如何成为常量如果它们是静态的final或final如何保证对象一旦创建,值就不会改变
class Television {
private final String MANUFACTURER;
private final int SCREEN_SIZE;
private boolean powerOn;
private int channel ;
private int volume ;
public Television(String MANUFACTURER, int SCREEN_SIZE) {
this.MANUFACTURER = MANUFACTURER;
this.SCREEN_SIZE = SCREEN_SIZE;
this.volume = volume;
}发布于 2015-01-05 21:03:29
我认为你混淆了变量是常量和类属性是不可变的。
而不提供setter。
您的电视对象可能具有不同的制造商和屏幕大小,因此您不能使用静态,因为这会使所有实例都相同。
此外,标准约定仅对常量使用CAPITALS_WITH_UNDERSCORES,例如static + final。
所以我将你的类声明为:
class Television {
private final String manufacturer;
private final int screenSize;
private boolean powerOn;
private int channel;
private int volume;
public Television(String manufacturer, int screenSize) {
this.manufacturer = manufacturer;
this.screenSize = screenSize;
this.volume = volume;
}
}并可能在其他地方将制造商声明为常量
public static final String SONY = "Sony";
public static final String SAMSUNG = "Samsung";发布于 2015-01-05 21:21:14
由于电视的制造商和屏幕大小不同,因此不需要静态关键字。我想您没有忘记在构造函数参数中提到体积。您的代码更改为如下所示。
class Television {
private final String manufacturer; // your declaration is correct as per your requirement but the naming convention is wrong final variables use lowerCamelCase instead of UPPERCASE.
private final int screenSize;
private boolean powerOn;
private int channel;
private int volume;
public Television(String manufacturer, int screenSize, int volume) {
this.manufacturer= manufacturer;
this.screenSize= screenSize;
this.volume = volume;
}
}不需要使用static final关键字,除非您声明了一些通用常量,例如:
public static final float pi = 3.14;它的值是相同的,而与对象或以其他方式称为实例无关。
发布于 2015-01-05 20:50:13
有三种形式的最终变量:
There is no requirement to initialize a final variable at declaration but it must initialize before using it.
You can only initialize a final variable once.
class Program {
/* Class Final Variables*/
//Static means its common for all the objects you are creating like tv1, tv2.....
static final int i1 = 10;
static final int i2;
static {
i2 = 10;
}
/*Instance Final Variables*/
final int i1 = 10;
final int i2;
final int i3;
{
i2 = 10;
}
Program() {
i3 = 10;
}
/*local final variable*/
final int i1 = 10;
final int i2;
i2 = 10;
}有关更多示例,请查看此where-can-final-variables-be-initialized
https://stackoverflow.com/questions/27779720
复制相似问题