问答详情
源自:7-4 Java 中的 this 关键字

访问方法的问题

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

}

}

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

提问者:lemon萌小2 2017-07-27 16:02

个回答

  • 慕无忌3126970
    2018-03-11 16:30:59

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

    }

    }


  • qq_BMW_3
    2017-07-27 16:14:56

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

    {

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

    }

    }


  • 慕无忌448502
    2017-07-27 16:14:05

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