Java实例变量

时间:2016-04-02 18:06:38

标签: java

我正在使用Codecademy学习Java。我正在尝试编写一个代码,使一个对象(在这种情况下是一只名为Spike的3岁狗)在nn = age上运行。我试过“暴力调试”,但那没用。我该如何更改“如何更改此项”以使代码生效?

class Dog {
    public Dog(int dogsAge) {
        int age = dogsAge;
    }

    public void bark() {
        System.out.println("Woof!");
    }

    public void run(int feet) {
        System.out.println("Your dog ran " + feet + " feet!");
    }

    public static void main(String[] args) {
        Dog spike = new Dog(3);
        spike.bark();
        spike.run(this.age); // How to change this?
    }
}

3 个答案:

答案 0 :(得分:3)

你的班级需要    - 为年龄变量添加存储空间    - 在construcor中设置该值    - 为您的主要功能提供访问它的方式

class Dog {
 private int age; //storage for the age value within the instance
 public Dog(int dogsAge){
   this.age = dogsAge; // set the value
 }
 // provide a way to access the age
 public int getAge() {
   return this.age;
 }
 public void bark(){
   System.out.println("Woof!");

 }
 public void run(int feet) {
   System.out.println("Your dog ran " + feet + " feet!");
 }


 public static void main(String[] args) {
  Dog spike = new Dog(3);
  spike.bark();
  spike.run(spike.getAge()); // retrieve the age and use it
 }

}

答案 1 :(得分:2)

class Dog {
int age;   //your mistake
 public Dog(int dogsAge){
 this.age = dogsAge;
 }
 public void bark() {
    System.out.println("Woof!");
}

public void run(int feet) {
    System.out.println("Your dog ran " + feet + " feet!");
}

public static void main(String[] args) {
    Dog spike = new Dog(3);
    spike.bark();
    spike.run(spike.age); // How to change this?
}

答案 2 :(得分:2)

尝试创建变量int age并在构造函数中初始化它,如下所示:

  class Dog {
  int age;
 public Dog(int dogsAge){
    this.age = dogsAge;
  }