1. 程式人生 > >public int/char get和public String get 區別

public int/char get和public String get 區別

通過一個程式的反覆除錯,更深刻理解了get的運用
get前面關於資料型別的寫法:
1,如果是單個的則寫當前的資料型別
2,如果要不同的資料型別放在一起則用String,而且需要return相合並如return.this.**+return.this.**


1,單個int或者char輸出場景
class student10{
  private   String name;
 private int age;
 private char gender;
 public  void setage(int age){
 this.age=age;
}
public int getage(){//此處若用name,則int改成char,單個返回用本身的數字型別
 return this.age;
}
}

public class A612{
 public static void main(String[]args){
  student10 one=new student10();
  one.setage(12);
  System.out.println(one.getage());
 }
}

2,整個輸出字串情形,tostring 必須要return this.name+this.age+this.gender這樣輸出才有效
class student11{
 private String name;
 private int age;
 private char gender;
 
public  void set(String name,int age,char gender){
 this.name=name;
 this.age=age;
 this.gender=gender;
}
public String get(){
 return this.name+this.age+this.gender;//toString 方法只能輸出字串,如果分別寫return則會輸出報錯
/* return this.age;
 return this.gender;//此處分別輸入則會報錯,因為定義了String*/
}
}

public class A6122{
 public static void main(String[]args){
  student11 one=new student11();
  /*one.setgender('男');*/
  one.set("nan",12,'男');
  /*System.out.println(one.getgender());*/
  System.out.println(one.get());
 }
}