在编程的过程中有时候我们需要通过一个静态的方法给静态的变量赋值,但是如果是直接赋值,编译器会直接报错:如下:
想必原因大家很清楚了,Cannot make a static reference to the non-static field mouthColor ;但是可以通过以下的方法间接赋值:
public class Duck {public String mouthColor = "";private Duck(String color) {mouthColor = color ;}public static Duck build(String color) {return new Duck(color);}public String getMouthColor() {return mouthColor;}public void setMouthColor(String mouthColor) {this.mouthColor = mouthColor;}}
调用方法:
public class Test {public static void main(String[] args) {Duck duck = Duck.build("黄色");System.out.println("鸭子的嘴是:"+duck.getMouthColor());}}
输出:
鸭子的嘴是:黄色
关键就是:通过静态的方法(new 一个对象返回)调用非静态的构造方法,再通过非静态的构造方法赋值非静态变量。这样就完成了静态方法间接赋值赋值非静态变量