我有两个类。Color.java和Light.java,我正在尝试使用Light类中的Color成员。而不使用Light类中的任何其他属性(我只需要下面两个。)我为Color类编写了一个toString方法、getters和setters。和一个复制构造函数。我只是没写在这里。这是一个练习。我不能在Light中使用extends或任何其他私人成员。奇怪的运动。(他们没有写我不能用extend。他们只是什么也没说)
public class Color
{
private int red;
private int green;
private int blue;
public Color(){
red = 0;
green = 0;
blue = 0;
}
}
我有轻型
public class Light
{
private Color color1;
private boolean switchedon;
public Light(int red, int green, int blue){
//dont know what to write here . how can i use the members of the Color class here ? without using extends. and without adding another attributes.
}
}
您可以
将Color
更改为具有另一个采用颜色值的构造函数
public class Color
{
private int red;
private int green;
private int blue;
public Color(){
red = 0;
green = 0;
blue = 0;
}
public Color(int red, int green, int blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
}
你可以
提供setter(和getter)来更改属性。。。
public class Color
{
private int red;
private int green;
private int blue;
public Color(){
red = 0;
green = 0;
blue = 0;
}
public void setRed(int red) {
this.red = red;
}
public void setGreen(int green) {
this.green = green;
}
public void setBlue(int blue) {
this.blue = blue;
}
public void getRed() {
return red;
}
// Other getters for green and blue...
}
你可以
两者都做。。。
你可以
从Color
扩展Light
,但仍然需要在Color
中提供构造函数和/或getter和setter
通过为color:中的字段提供color和/或getter和setter的构造函数
Color(int red, int green, int blue) {
this.red = red;
etc....