如何在对象中找到参数的值?

时间:2017-02-04 21:57:32

标签: java

我正在创建一个涉及具有随机参数的对象的代码。有没有办法可以访问这些参数的值?

public class Bicycle{

  public Bicycle(int startCadence, int startSpeed, int startGear) {
      int gear = startGear;
      int cadence = startCadence;
      int speed = startSpeed;
  }

  public static void main(String[] args){
    Bicycle myBike = new Bicycle(30, 0, 8);
    int current_gear = myBike.gear; // accessing the value of gear
  }
}

说我想要访问当前档位的值。我将如何去做

3 个答案:

答案 0 :(得分:0)

在类构造函数之外声明gear,然后您可以通过两种方式访问​​它。

1 - 如果gearpublic,您可以

访问它
Bicycle myBike = new Bicycle(30, 0, 8);
int current_gear = myBike.gear;

2 - 如果gearprivate,您需要一个返回gear的公共方法

public int get_gear()
{
    return gear;
}

然后访问它

Bicycle myBike = new Bicycle(30, 0, 8);
int current_gear = myBike.get_gear();

答案 1 :(得分:0)

public class Bicycle{
  private int gear;

  public int getGear()
  {return this.gear;}

  public Bicycle(int startCadence, int startSpeed, int startGear) {
      this.gear = startGear;
      int cadence = startCadence;
      int speed = startSpeed;
  }

  public static void main(String[] args){
    Bicycle myBike = new Bicycle(30, 0, 8);
    int current_gear = gear.myBike();
    int theGearIWanted = myBike.getGear();
  }
}

答案 2 :(得分:-1)

public class Bicycle{ 
    int gear;
    int cadence;
    int speed;
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear; 
        cadence = startCadence; 
        speed = startSpeed; } 
    public static void main(String[] args){ 
        Bicycle myBike = new Bicycle(30, 0, 8); 
        int current_gear = myBike.gear; }
}

这样,您将gear变量设为成员变量。然后,只要您需要访问它,请使用myBike.gear。或者,您可以为您的Bicycle类添加get方法。像这样:

public int getGear(){
    return gear;
}