【问题标题】:Instance variables with a method in Java?Java中带有方法的实例变量?
【发布时间】:2013-10-09 04:20:23
【问题描述】:

三角形方法有 3 个实例变量。 诠释侧1,侧2,侧3;

他们给了我作为公共三角形(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) {

}

谢谢

我把它和构造函数搞混了。想通了,谢谢各位。

【问题讨论】:

  • 这取决于您在第一句话中的意思是“三角形类有三个实例变量”还是“三角形方法有三个参数”。你实际写的没有意义。方法没有实例变量。
  • 第二段代码甚至无法编译...一个类不能有这样的参数。
  • 我认为遵循 Java 编程教程是个好主意。在开始编码之前了解语言的主要概念很重要:)。你可以从docs.oracle.com/javase/tutorial开始

标签: java variables instance


【解决方案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;
    }
}

【讨论】:

  • 请问类名可以使用大写字母吗?你在这里教 OP。请务必把好东西教给他。
  • @DavidWallace 是的。我回答引用了 Ryan 的代码,这就是我使用小写字母的原因。
【解决方案2】:
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;

    }
}

希望这会有所帮助。 谢谢

【讨论】:

  • 既然您已经将一段代码倾倒到了一个意想不到的海报上,您可能想向他们解释为什么这种方法适合他们的需求;)
【解决方案3】:

最佳实践是

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

【讨论】:

  • 最佳实践不包括使用小写的类名。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多