public class Something {
public static void main(String[] args) {
Something s = new Something();
System.out.println("s.doSomething() returns " + doSomething());//在main这个静态方法中引用了非静态方法。静态方法只能引用静态成员
}
public String doSomething() {
return "Do something ...";
}
}
可以将该题目改正:
1.就作者本身做法而言,可以利用对象 s进行应用改为:
System.out.println("s.doSomething() returns " +s.doSomething());
2.利用本身类名创建匿名对象引用:
public static void main(String[] args) {
Something s = new Something();//去掉此句
System.out.println("s.doSomething() returns " + new Something().doSomething());
}
3.将被引用的doSomething方法改为静态方法:
public static String doSomething() {
return "Do something ...";
}
4.将被引用方法改为静态后,在对输出语句修改,直接改为类名调用静态方法名():
System.out.println("s.doSomething() returns " + Something.doSomething());
|