set field等于java中方法的参数

时间:2016-03-17 03:24:16

标签: java methods field

所以我的代码看起来像这样:

$sample_date = "2016-01-01 02:00:00";

我在另一个类中声明了testName和testAge,但我需要在我的字段中访问它们,以便我可以在其他方法中使用它们。现在我只能在METHODNAME方法中访问testAge和testName。

非常感谢任何帮助:)

2 个答案:

答案 0 :(得分:1)

您应该添加 getters setters (也称为访问者 mutators )。对于Example

public class Example {
    public Example(String name, int age) {
        this.name = name;
        this.age = age;
    }

    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

然后,您可以修改(或检索)该类的实例中的值。

答案 1 :(得分:0)

你可以在这里使用继承。 Parent class有一些方法。您将子类扩展到父类。并且您将从child class

获取全部parent class.

父类也需要getter/setter

有一个完整的例子:按照这个

//显示车辆属性的类

class Vehicle {
   String color;
   private int speed;
   private int size;
   public int getSize() {
      return size;
   }
   public int getSpeed() {
      return speed;
   }
   public void setSize(int i) {
      size = i;
   }
   public void setSpeed(int i) {
      speed = i;
   }
}

// A subclass which extends for vehicle
class Car extends Vehicle {
   int CC;
   int gears;
   int color;
   void attributescar() {
       // Error due to access violation
      // System.out.println("Speed of Car : " + speed); 
      // Error due to access violation
      //System.out.println("Size of Car : " + size); 
   }
}
public class Test {
   public static void main(String args[]) {
     Car b1 = new Car();
     // the subclass can inherit 'color' member of the superclass
     b1.color = 500; 
     b1.setSpeed(200) ;
     b1.setSize(22);
     b1.CC = 1000;
     b1.gears = 5;
     // The subclass refers to the members of the superclass
     System.out.println("Color of Car : " + b1.color);
     System.out.println("Speed of Car : " + b1.getSpeed());
     System.out.println("Size of Car : " + b1.getSize());
     System.out.println("CC of Car : " + b1.CC);
     System.out.println("No of gears of Car : " + b1.gears);
  }
}

资源链接:http://beginnersbook.com/2013/03/inheritance-in-java/