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 }