简体   繁体   中英

Instance variables with a method in Java?

A triangle method has 3 instance variables. int side1, side2, side3;

They give me the method I need to make as public Triangle (int s1, int s2, int s3)

Do I declare it as:

   public class triangle {

private int s1;
private int s2;
private int s3;

}

OR

  public class triangle (int s1, int s2, int s3) {

}

Thanks

I got this mixed up with a constructor. Figured it out, thanks guys.

First of all, if the method name is same as class name then it is called constructor which is called when a new object of that class is created.

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;

    }
}

Hope this helps. Thanks

The best practice is

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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