1.封裝java
1 class Dog{ 2 String name;//成員變量
3 int age; 4 private char genter;//加private變爲私有屬性,要提供方法才能在外部進行調用
5
6 public void setGenter(char genter){ 7 //加if語句能夠防止亂輸入
8 if(genter=='男'||genter=='女'){ 9 this.genter=genter;//this.name,這個name爲成員變量
10 }else{ 11 System.out.println("請輸入正確的性別"); 12 } 13 } 14 public char getGenter(){ 15 return this.genter; 16 } 17
18 } 19 public class Test1{ 20 public static void main(String[] args){ 21 Dog one=new Dog(); 22 one.setGenter('女'); 23 System.out.println(one.getGenter()); 24
25 } 26 }
2.方法的重載函數
方法的重載是指一個類中能夠定義有相同的名字,但參數不一樣的多個方法,調用時會根據不一樣的參數列表選擇對應的方法。this
1 class Cal{ 2 public void max(int a,int b){ 3 System.out.println(a>b?a:b); 4 } 5 public void max(double a,double b){ 6 System.out.println(a>b?a:b); 7 } 8 public void max(double a,double b,double c){ 9 double max=a>b?a:b; 10 System.out.println(max>c?max:c); 11 } 12
13 } 14 public class Test1{ 15 public static void main(String[] args){ 16 Cal one=new Cal(); 17 one.max(88.9,99.3,120); 18
19 } 20 }
3.構造方法(構造函數)spa
1 class Dog{ 2 private String name; 3 private int age; 4 Dog(String name,int age){//構造方法,public可加可不加
5 this.name=name; 6 this.age=age; 7 System.out.println("名字:"+this.name+"年齡:"+this.age); 8 } 9 Dog(){ 10 } 11 void get(){//普通方法,public可寫可不寫
12 System.out.println("我是一個普通方法"); 13 } 14
15 } 16 public class Test1{ 17 public static void main(String[] args){ 18 Dog one=new Dog("小明",26); 19 Dog two=new Dog(); 20 one.get(); 21 two.get(); 22
23 } 24 }