调用类方法和调用实例方法有什么区别?

时间:2015-01-06 06:25:45

标签: java

我想知道调用类方法调用实例方法之间的区别?

不是类方法:

identifier(); 

和实例方法如:

object.identifier();

如果我错了,请纠正我。

2 个答案:

答案 0 :(得分:2)

(我认为,你的意思是.();类似于myClassInstance.myMethod();如果是,那么:)

类方法是static方法,可以在加载类时调用。它们不需要调用类的实例。假设你创建了一个这样的类:

class MyClass {
    public static void classMethod() {
        /* Something to do (statically) here */
    }
    public void instanceMethod() {
        /* Some thing to do here */
    }

正如您所看到的,一旦您在工作区中导入类,就可以调用静态(类)方法,如下所示:

MyClass.classMethod();

但是不是实例方法,调用实例方法需要调用类的实例,如下所示:

MyClass mc = new MyClass();
mc.instanceMethod();

另请注意,static方法只允许static工作(!)。喜欢改变静态变量或调用静态函数。 这个答案也有帮助。 Difference between Static methods and Instance methods

答案 1 :(得分:0)

简单地说, class method ("静态方法")是WHOLE类的属性,因此它被称为className.methodName()

instance methods ,则每个对象都有自己的副本,因此称为objectName.instanceMethodName().

第二个区别:

  • class(" static")方法只能访问静态字段
  • 但实例方法可以访问该类的任何字段。

第三个有点高级差异是类 (Static) methods are bound to the class at compile time ,而 instance methods are bound to their objects at run time ..

相关问题