一、類的方法
上一節(jié)我們學(xué)習(xí)了類中包含屬性,在這一節(jié)我們學(xué)習(xí)類中的一個(gè)重要知識(shí)點(diǎn):方法。
方法的一般語(yǔ)法格式:修飾符 返回值類型 方法名(參數(shù)列表){方法體}
例如: public void ptln(string name){}這就是一個(gè)方法。
這里借用上一節(jié)的例子。
1.1 定義類
例如:(在編寫代碼中,雖然寫注釋會(huì)占用一點(diǎn)時(shí)間,但是寫注釋是一個(gè)很好的習(xí)慣)
public class student//類名
{
public string id; //學(xué)號(hào)
public string name;//名字
public int age;//年齡
public boolean sex;//性別
public void ptln()//方法:打印姓名
{system.out.println(name);}}
1.2 調(diào)用方法(打印姓名“小王”)
student m_stu=new student();//使用關(guān)鍵字“new”創(chuàng)建student類型的對(duì)象。
m_stu.name="小王";
m_stu.ptln();
二、參數(shù)列表
定義時(shí):
public void ptln(boolean is_pass,int score)//參數(shù)列表以逗號(hào)分開
{
if(is_pass)
system.out.println(name+"成績(jī)合格,成績(jī):");
else
system.out.println(name+"成績(jī)不合格,成績(jī):"+score);
}
調(diào)用時(shí):
student m_stu=new student();//使用關(guān)鍵字“new”創(chuàng)建student類型的對(duì)象。
m_stu.name="小王";
m_stu.ptln(false,26);//打印小王成績(jī)不合格,成績(jī):26:
三、返回類型
方法分為有返回和無(wú)返回,無(wú)返回使用關(guān)鍵詞“void”,否則輸入真實(shí)返回類型。
1.1 定義類
定義時(shí):
public boolean ptln(int score)//返回類型Boolean
{
if(score>=60)
return true;//使用關(guān)鍵詞“return”返回值
else
return false;
}
調(diào)用時(shí):
student m_stu=new student();//使用關(guān)鍵字“new”創(chuàng)建student類型的對(duì)象。
boolean is_pass=m_stu.ptln(26);//此時(shí)is_pass應(yīng)為false;
四、方法名的重載(overload)
在java中允許方法名相同,參數(shù)列表不同的方法同時(shí)存在,調(diào)用時(shí)根據(jù)參數(shù)列表判斷。
例如:
public class test
{
public void test(){}
public void test(string a){}
public void test(string a,int b){}
}
五、構(gòu)造方法
可在構(gòu)造對(duì)象時(shí)初始化屬性的值。
例如:
public class test
{
string a;int b;
public void test(){}//默認(rèn)構(gòu)造函數(shù),自動(dòng)生成,可不寫
public void test(string a)
{
this.a=a;
}
public void test(string a,int b)
{
this.a=a;this.b=b;
}}
調(diào)用: test m_t=new test("小王",26);int m_b=m_t.b;//m_b的值為26;
六、靜態(tài)方法
在類中與類中屬性不相關(guān),即無(wú)需使用this的方法,可以添加static使之成為靜態(tài)方法。
例如:
public class student//類名
{
public string id; //學(xué)號(hào)
public void ptln()//ptln()方法與類中屬性無(wú)關(guān),添加static
{system.out.println(“小王”);}}
修改為:
public static void ptln()//方法:打印姓名
{system.out.println(“小王”);}
調(diào)用時(shí)直接使用類名,無(wú)需創(chuàng)建對(duì)象:student.ptln();