lemon萌小2
2017-07-27 16:02
package text2;
public class HelloWorld {
int age;
public void print(int age) {
this.age=age;
System.out.println(this.age);
}
public static void main(String[] args) {
//HelloWorld th=new HelloWorld();
//th. print(23);
HelloWorld.print(23);
}
}
请问为什么我在主函数中通过类名加方法访问非静态的方法不对呢??
在主函数中通过类名加方法访问非静态的方法,是对的。把之前的注释符号去掉,然后注释掉HelloWorld.print(23);运行就对了
public class HelloWorld {
int age;
public void print(int age) {
this.age=age;
System.out.println(this.age);
}
public static void main(String[] args) {
HelloWorld th=new HelloWorld();
th. print(23);
//HelloWorld.print(23);
}
}
类中的方法是不能被类中的其他方法直接引用的,如果要引用首先为类创建一个对象再使用。你之前的方法是对的为什么要注释掉呢?
{
int age;
public void print(int age) {
this.age=age;
System.out.println(this.age);
}
public static void main(String[] args) {
HelloWorld th=new HelloWorld();
th. print(23);
//HelloWorld.print(23);
}
}
main主函数是带了static的,是静态方法,在静态方法中肯定不可以直接引用非静态方法啊
Java入门第二季
531660 学习 · 6329 问题
相似问题