簡體   English   中英

Java - 使用 class 實例引用 static 方法

[英]Java - Referring static method using that class instance

使用 class 實例使用 static 方法時究竟會發生什么? 在構建級別和運行時。

提前致謝。

更新:有兩個類,class 一個有一個方法,第二個使用該方法,一段時間后該方法更改為 static。 運行時,我得到 IncompatibleClassChangeError。

If you call a static method from a class instance, it is identical to calling it in the standard static fashion (ie from the class name.) The compiler is smart enough to know to make the static call.

如果你的意思是

class Foo {
  static void bar() { ... }
}

public class Baz {
  public static void main(String... argv) {
    new Foo().bar();  // Use static method here via instance
  }
}

然后該實例將被完全忽略。

如果你通過反射來做,那么它也會被忽略。

如果底層方法是 static,則忽略指定的 obj 參數。 它可能是 null。

考慮這種情況......

Class XYZ{

public static void functionTest(){
 // Your code
}

public static void main(String args[]){
XYZ x = new XYZ();
//Here we can execute the method functionTest() in 2 ways.
x.functionTest();
XYZ.functionTest();
}
}

Every class will have something called Context of a class , which means all the static methods and static variables get memory allocated in RAM without creating an object of that class and we call that memory as Context of a class.

一個reference(x)包含兩部分,一個是對象(instance)的實際地址,另一個是class的上下文地址。

當我們在上面的場景中調用 x.function() 時,首先它總是搜索 class 的上下文,如果找到它就會執行它,如果找不到它就會從 class 的實例中執行它。

因此,無論您以何種方式嘗試執行 static 方法,它將始終從 class 的上下文中執行,而不是從 class 的實例中執行。

這就是為什么可以以兩種方式調用 class 的 static 成員的原因。

並且通過從實例調用該方法,我們沒有必要創建根本不需要的 object(不必要的內存分配)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM