三角形方法有3个实例变量。 int side1,side2,side3;
他们给了我需要做的公共Triangle方法(int s1,int s2,int s3)
我是否将其声明为:
public class triangle {
private int s1;
private int s2;
private int s3;
}
OR
public class triangle (int s1, int s2, int s3) {
}
由于
我把它与构造函数搞混了。想出来,谢谢你们。
答案 0 :(得分:1)
首先,如果方法名称与类名相同,则称为constructor
,在创建该类的新对象时调用它。
public class Triangle {
private int s1; // This are the private variable which
private int s2; // are accessed by only object of
private int s3; // class triagnle.
public class Triangle (int s1, int s2, int s3) // This is a constructor which is called
{ // when you create a object with new keyword
this.s1 = s1; // like Triangle t = new Triangle(1,2,3);
this.s2 = s2;
this.s3 = s3;
}
}
答案 1 :(得分:0)
public class triangle {
int s1;
int s2;
int s3;
public triangle (int s1, int s2, int s3) {
this.s1 = s1;
this.s2 = s2;
this.s3 = s3;
}
}
希望这会有所帮助。 感谢
答案 2 :(得分:0)
最佳做法是
public class Triangle {
//atributes
private int s1;
private int s2;
private int s3;
//encapsulation
public int getS1() {
return s1;
}
public int getS2() {
return s2;
}
public int getS3() {
return s3;
}
public void getS1(int value){
this.s1 = value;
}
public void getS2(int value){
this.s2 = value;
}
public void getS3(int value){
this.s3 = value;
}
//constructor
public Triangle (int s1, int s2, int s3)
{
this.s1 = s1;
this.s2 = s2;
this.s3 = s3;
//do something
}
}