繁体   English   中英

用Java中的方法实例化变量?

[英]Instance variables with a method in Java?

三角形方法具有3个实例变量。 int side1,side2,side3;

他们给了我我需要制作为公共三角形的方法(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) {

}

谢谢

我将其与构造函数混合在一起。 弄清楚了,谢谢大家。

首先,如果方法名称与类名称相同,则称为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;
    }
}
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;

    }
}

希望这可以帮助。 谢谢

最佳做法是

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
 }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM