class method 同instance method 有咩唔同? 點樣分?

2006-11-29 5:41 pm
java 的class method 同instance method 有咩唔同? 點樣分?


thx~~

回答 (2)

2006-11-30 10:02 am
✔ 最佳答案
樓上的朋右有少少錯誤呢~

System.out.println() 這句 statement 中的 println() 可不是 class/static method 呢,反而 out 這個 PrintStream 物件才是 static。

給發問者的例子:
(1) class/static method
System.currentTimeMillis() // 取得目前系統時間

(2) instance method
String helloString = new String("hello");
helloString.equals( "hope this can help you" ); // 測試兩個 String 的文字是否相等

case 1:不用 create any object 便可以 invoke method currentTimeMillis(),此為 class/static method

case 2:雖要先建立物件,才可透過該物件的 reference 去 invoke 它的 method,這就是 instance method
2006-11-29 5:51 pm
Hope these helps:
http://scv.bu.edu/Doc/Java/tutorial/java/anatomy/static.html
http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html

Basically a method invoked from a class instead of an object is a class method - usually those that are declared static within a class - for example, System.out.println()
you don't need to instantiate a System instance in order to invoke the method.

All the other methods are instance method. Typically you need to declare the class instance and then invoke the method within that instance.

2006-11-30 09:30:47 補充:
Okay, I took it back re examples for class method - System.out.println() is not a clear enough example. One obvious example for Class Method is the Double.toString() or Integer.toString() methods etc that are often used.


收錄日期: 2021-04-15 23:50:19
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20061129000051KK00648

檢視 Wayback Machine 備份