为了账号安全,请及时绑定邮箱和手机立即绑定

访问方法的问题

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);

}

}

请问为什么我在主函数中通过类名加方法访问非静态的方法不对呢??

正在回答

3 回答

在主函数中通过类名加方法访问非静态的方法,是对的。把之前的注释符号去掉,然后注释掉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);

}

}


0 回复 有任何疑惑可以回复我~

类中的方法是不能被类中的其他方法直接引用的,如果要引用首先为类创建一个对象再使用。你之前的方法是对的为什么要注释掉呢?

{

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);

}

}


0 回复 有任何疑惑可以回复我~

main主函数是带了static的,是静态方法,在静态方法中肯定不可以直接引用非静态方法啊

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
Java入门第二季 升级版
  • 参与学习       530715    人
  • 解答问题       6091    个

课程升级!以终为始告别枯燥,在开发和重构中体会Java面向对象编程的奥妙

进入课程

访问方法的问题

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信