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

如题所述

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关键字的方法,在类定义时没有占用内存,只有在类被实例化成对象时,对象调用该方法才被分配内存。

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

温馨提示:答案为网友推荐,仅供参考
相似回答