java主方法如何调用非静态方法

public class Test
{
private int a;
public int getnumber()
{
setnumber(8);
return this.a;
}
public int setnumber(int a)
{
return this.a=a;
}

public static void main(String args[])
{

}

}
如题我该怎么写main方法调用getnumber并输出a呢

java主方法调用非静态方法的步骤:

    1、新建一个类,本例类名“NoStaticMethod”,声明一些成员变量,创建一个主方法main(),一个非静态方法Method_1()。

    2、类的全部代码。

** * Created by Administrator on 2016/7/25.

*/

public class NOstaticMethod {

//satement new variable name: studentName

public static String studentName = "xxx";

//satetment new variable nmae: country

public static String country;

//satement new variable name: nation

private static String nation;

//satement new variable name: subject

public String subject = "物理";

//satement new variable name: school

private String school;

//create main method

public static void main(String[] args) {

//NOstaticMethod.Method_1(); 在静态方法main中是不能直接调用非静态方法Method_1的

//只能通过创建类的对象,再由对象去调用成员方法以及成员变量。

NOstaticMethod wangyan = new NOstaticMethod();

//call methol

wangyan.Method_1();

// String physics= subject;在静态方法中也是不能访问非静态成员变量的

//call not static  variable

String physics = wangyan.subject;

System.out.println("在主方法main()中只能通过对象来调用非静态成员变量subject:" + physics);

}  

//create  new method name: Method_1()

public void Method_1() {

System.out.println("Method_1是一个公共的、非静态的方法");

System.out.println("在非静态方法Method_1中访问静态成员变量“学生姓名”(studentName):" + studentName);

System.out.println("在method_1中直接调用非静态成员变量subject:" + subject);

}

    3、运行结果

Method_1是一个公共的、非静态的方法

在非静态方法Method_1中访问静态成员变量“学生姓名”(studentName)

在method_1中直接调用非静态成员变量subject(科目)

在主方法main()中只能通过对象来调用非静态成员变量subject

    4、分析代码

public static void main(String[] args) {

//NOstaticMethod.Method_1(); 在静态方法main中是不能直接调用非静态方法Method_1的

//只能通过创建类的对象,再由对象去调用成员方法以及成员变量。

NOstaticMethod wangyan = new NOstaticMethod();

//call methol

wangyan.Method_1();

// String physics= subject; 在静态方法中也是不能访问非静态成员变量的

//call not static  variable

String physics = wangyan.subject;

System.out.println("在主方法main()中只能通过对象来调用非静态成员变量subject:" + physics);

}

静态方法与非静态方法的区别:

静态方法是在类中使用staitc修饰的方法,在类定义的时候已经被装载和分配。而非静态方法是不加static关键字的方法,在类定义时没有占用内存,只有在类被实例化成对象时,对象调用该方法才被分配内存。

其次,静态方法中只能调用静态成员或者方法,不能调用非静态方法或者非静态成员,而非静态方法既可以调用静态成员或者方法又可以调用其他的非静态成员或者方法。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-02-27
public class Test {
private int a;

public int getnumber() {
setnumber(8);
return this.a;
}

public int setnumber(int a) {
return this.a = a;
}

public static void main(String args[]) {
Test t = new Test();
// t.setnumber(10);
int a = t.getnumber();
System.out.println(a);
}

}

本回答被提问者和网友采纳
第2个回答  2014-02-14
实例化对象,new Test().getnumber();就ok了 还可以把方法变为static的 就可以直接调用了
第3个回答  2014-02-14

用类初始化对象,对象去调用咯

追问

额,能给写出来吗,初学者不懂

相似回答