一常遂、類(lèi)的方法
上一節(jié)我們學(xué)習(xí)了類(lèi)中包含屬性,在這一節(jié)我們學(xué)習(xí)類(lèi)中的一個(gè)重要知識(shí)點(diǎn):方法柠贤。
方法的一般語(yǔ)法格式:修飾符 返回值類(lèi)型 方法名(參數(shù)列表){方法體}
例如: public void ptln(string name){}這就是一個(gè)方法。
這里借用上一節(jié)的例子类缤。
1.1 定義類(lèi)
例如:(在編寫(xiě)代碼中臼勉,雖然寫(xiě)注釋會(huì)占用一點(diǎn)時(shí)間,但是寫(xiě)注釋是一個(gè)很好的習(xí)慣)
public class student//類(lèi)名
{
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類(lèi)型的對(duì)象呀非。
m_stu.name="小王";
m_stu.ptln();
二坚俗、參數(shù)列表
定義時(shí):
public void ptln(boolean is_pass,int score)//參數(shù)列表以逗號(hào)分開(kāi)
{
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類(lèi)型的對(duì)象猖败。
m_stu.name="小王";
m_stu.ptln(false,26);//打印小王成績(jī)不合格,成績(jī):26:
三降允、返回類(lèi)型
方法分為有返回和無(wú)返回恩闻,無(wú)返回使用關(guān)鍵詞“void”,否則輸入真實(shí)返回類(lèi)型剧董。
1.1 定義類(lèi)
定義時(shí):
public boolean ptln(int score)//返回類(lèi)型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類(lèi)型的對(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)生成,可不寫(xiě)
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)方法
在類(lèi)中與類(lèi)中屬性不相關(guān)础倍,即無(wú)需使用this的方法烛占,可以添加static使之成為靜態(tài)方法。
例如:
public class student//類(lèi)名
{
public string id; //學(xué)號(hào)
public void ptln()//ptln()方法與類(lèi)中屬性無(wú)關(guān)沟启,添加static
{system.out.println(“小王”);}}
修改為:
public static void ptln()//方法:打印姓名
{system.out.println(“小王”);}
調(diào)用時(shí)直接使用類(lèi)名忆家,無(wú)需創(chuàng)建對(duì)象:student.ptln();