首先我们要逐一研究,首先是静态方法,最后是非静态方法。
我们必须使用静态关键字来声明或定义静态方法。
静态方法与类相关联,这意味着可以使用类名,对象或对象或不使用对象(直接调用)来调用这些方法,无需为静态方法声明任何对象。
静态方法只能访问静态成员,而静态方法属于同一类或不同类,这意味着静态方法不能访问非静态成员或方法。
静态方法仅创建整个程序的一个副本,并与其他成员或方法共享。
示例
//显示静态成员和方法的行为 class StaticClass { //声明一个静态方法 public static int div(int a, int b) { return a / b; } } public class Main { public static void main(String[] args) { int p = 10, q = 5; //声明一个静态成员 String str = "Welcome in Java World"; //调用静态方法 int div = StaticClass.div(p, q); /* Here we are calling static methods directly without objects or classname. If we want to call with classname or with object then also not a problem. */ System.out.print("The value of str is = " + str); System.out.print("The divide of two number is = " + div); } }
输出结果
D:\Programs>javac Main.java D:\Programs>java Main The value of str is = Welcome in Java World The divide of two number is = 2
在方法名称之前,我们不得使用静态关键字来声明或定义静态方法。
非静态方法与类无关,这意味着不能使用类名称调用这些方法,并且必须声明对象,并且可以使用对象名称来调用非静态方法。
非静态方法可以访问静态成员和静态方法,非静态成员和非静态方法属于同一类或不同类,但非静态不能修改静态成员或方法的值。
对于非静态方法,请创建所有对象的单独副本,或者换句话说,请创建所有对象的单独副本。
示例
class NonstaticClass { //声明一个非静态方法 public int div(int a, int b) { return a / b; } } public class Main { public static void main(String[] args) { int p = 10, q = 5; //声明一个NonstaticClass对象 NonstaticClass nc = new NonstaticClass(); int div = nc.div(p, q); //使用类对象调用非静态方法。 System.out.print("The div of two num is = " + div); } }
输出结果
D:\Programs>javac Main.java D:\Programs>java Main The div of two num is = 2