十年網(wǎng)站開發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營(yíng)維護(hù)+專業(yè)推廣+無(wú)憂售后,網(wǎng)站問題一站解決
這篇文章主要介紹Java基礎(chǔ):封裝、方法重載、構(gòu)造方法是什么,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
1.封裝
class Dog{ String name;//成員變量 int age; private char genter;//加private變?yōu)樗接袑傩?,要提供方法才能在外部進(jìn)行調(diào)用 public void setGenter(char genter){ //加if語(yǔ)句可以防止亂輸入 if(genter=='男'||genter=='女'){ this.genter=genter;//this.name,這個(gè)name為成員變量 }else{ System.out.println("請(qǐng)輸入正確的性別"); } } public char getGenter(){ return this.genter; } } public class Test1{ public static void main(String[] args){ Dog one=new Dog(); one.setGenter('女'); System.out.println(one.getGenter()); } }
2.方法的重載
方法的重載是指一個(gè)類中可以定義有相同的名字,但參數(shù)不同的多個(gè)方法,調(diào)用時(shí)會(huì)根據(jù)不同的參數(shù)列表選擇對(duì)應(yīng)的方法。
class Cal{ public void max(int a,int b){ System.out.println(a>b?a:b); } public void max(double a,double b){ System.out.println(a>b?a:b); } public void max(double a,double b,double c){ double max=a>b?a:b; System.out.println(max>c?max:c); } } public class Test1{ public static void main(String[] args){ Cal one=new Cal(); one.max(88.9,99.3,120); } }
3.構(gòu)造方法(構(gòu)造函數(shù))
class Dog{ private String name; private int age; Dog(String name,int age){//構(gòu)造方法,public可加可不加 this.name=name; this.age=age; System.out.println("名字:"+this.name+"年齡:"+this.age); } Dog(){ } void get(){//普通方法,public可寫可不寫 System.out.println("我是一個(gè)普通方法"); }14 15 }16 public class Test1{ public static void main(String[] args){ Dog one=new Dog("小明",26); Dog two=new Dog(); one.get(); two.get(); } }
以上是Java基礎(chǔ):封裝、方法重載、構(gòu)造方法是什么的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)成都網(wǎng)站設(shè)計(jì)公司行業(yè)資訊頻道!
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。