java靜態(tài)方法和實例方法的區(qū)別
靜態(tài)方法(方法前冠以static)和實例方法(前面未冠以static)的區(qū)別
調(diào)用靜態(tài)方法或說類方法時,可以使用類名做前綴,也可以使用某一個具體的對象名;通常使用類名。
static方法只能處理static域或靜態(tài)方法。實例方法可以訪問實例域, 靜態(tài)域或靜態(tài)方法, 記住都行。
本章源碼
class StaticTest {
static int a = 4;
static int b = 9;
static void call() {
/*下一句是錯誤的,因為靜態(tài)的不能調(diào)用實例的方法。*/
//callins();
System.out.println("a = " + a+"馬克-to-win"+Test.c);//靜態(tài)方法可以訪問靜態(tài)屬性
}
void callins() {
call();
System.out.println("a = " + a+"實例馬克-to-win"+Test.c);//靜態(tài)方法可以訪問靜態(tài)屬性
}
}
public class Test {
static int c = 43;
public static void main(String args[]) {
/*剛運行到這一步時,debug觀察,StaticTest.a的值就等于4,Test.c的值就等于43,
說明系統(tǒng)在我們的程序一開始時,就會給所有的類變量賦值。如果是對象參考, 就是null,
見photoshop的例子*/
StaticTest se =new StaticTest();
System.out.println("開始觀察StaticTest.a和Test.c");
se.b=5;
StaticTest.call();//靜態(tài)方法用類名直接調(diào)用
se.call();
se.callins();
System.out.println("b = " + StaticTest.b);//靜態(tài)屬性用類名直接調(diào)用
}
}
result is:
開始觀察StaticTest.a和Test.c
a = 4馬克-to-win43
a = 4馬克-to-win43
a = 4馬克-to-win43
a = 4實例馬克-to-win43
b = 5
馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203。
assignment: make a method which can print "hello world!".
本章源碼
package com;
class Car{
static int count = 0;
Car() {
count++;//實例方法可以訪問靜態(tài)變量
}
static int getCount(){
return count;
}
int inscal()
{
return getCount();//實例方法可以調(diào)用靜態(tài)方法。
}
}
public class Test{
public static void main(String[] args){
System.out.println(Car.getCount());//it's ok
Car c = new Car();
System.out.println(c.getCount());//實例可以調(diào)用靜態(tài)方法。馬克-to-win
System.out.println(Car.getCount());
Car c1 = new Car();
System.out.println(Car.getCount());
System.out.println(c1.inscal());
}
}
result is:
0
1
1
2
2