三角形方法有 3 个实例变量。 int 边1、边2、边3;
他们给了我需要制作为 public Triangle (int s1, int s2, int s3) 的方法
我是否将其声明为:
public class triangle {
private int s1;
private int s2;
private int s3;
}
或者
public class triangle (int s1, int s2, int s3) {
}
谢谢
我把它和构造函数搞混了。明白了,谢谢各位。
最佳答案
首先,如果方法名称与类名称相同,则称为构造函数
,该构造函数在创建该类的新对象时调用。
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;
}
}
关于java - Java 中方法的实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19263056/