java中如何才能调用非静态方法

时间:2024-10-11 22:10:37

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

java中如何才能调用非静态方法

2、step2:类的全部代码** * Created by Administrator on 2016/壅酪认奉7/25.* 本例专门探究方法的调用问题。*/public class NOstaticMethod { //satement new variable name: studentName public static String studentName = "王燕"; //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、step3:运行结果Method_1是一个公共的、非静态的方法在非静态方法Method_1中访问静态成员变量“学生姓名”(studentName):王燕在method_1中直接调用非静态成员变量subject:物理在主方法main()中只能通过对象来调用非静态成员变量subject:物理

4、step4:分析代码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); }解释: 1、由于Method_1()是非静态方法,在main()中不能直接调用 所以:NOstaticMethod.Method_1(); 这样调用 会出错。 2、由于subject;是非静态成员方法,同样在main()不能直接调用 所以:String physics= subject; 这样调用也会出错。 3、所以只能通过先创建类的对象,再由对象去调用非静态成员方法和非静态成员变量。 NOstaticMethod wangyan = new NOstaticMethod(); wangyan.Method_1(); String physics = wangyan.subject;

5、step5:小结在同一类内,调用非静态成员方法和非静态成员变量的步骤及格式第一:创建类的对象 类名 对象名=new 类名( );第二:调用方法或变量 对象名.成员方法名(); 数据类型 变量名= 对象名.成员变量名;

© 手抄报圈