按要求編寫Java應用程序。
(1)創建一個叫做People的類:
屬性:姓名、年齡、性別、身高 行為:說話、計算加法、改名
編寫能為所有屬性賦值的構造方法;
(2)創建主類:
創建一個對象:名叫“張三”,性別“男”,年齡18歲,身高1.80;
讓該對象調用成員方法:1)說出“你好!” 2) 計算23+45的值 3) 將名字改為“李四”
1 public class People { 2 3 private String name; 4 private String sex; 5 private int age; 6 private double height; 7 8 public String getName() { 9 return name; 10 } 11 12 public void setName(String name) { 13 this.name = name; 14 } 15 16 People(String name, String sex, int age, double height) { 17 this.name = name; 18 this.sex = sex; 19 this.age = age; 20 this.height = height; 21 } 22 23 public void sayHi() { 24 System.out.println(this.name + ": 你好!"); 25 } 26 27 public double doAdd(double a, double b) { 28 return a + b; 29 } 30 31 public void gaiMingZi(String name) { 32 this.name = name; 33 34 } 35 36 public static void main(String[] args) { 37 People p1 = new People("張三", "男", 18, 180); 38 39 p1.sayHi(); 40 System.out.println("23+45=" + p1.doAdd(23, 45)); 41 p1.gaiMingZi("李四"); 42 System.out.println("大家好,我是: " + p1.name); 43 System.out.println(p1.name + "的個人信息:" + p1.toString()); 44 } 45 46 @Override 47 public String toString() { 48 return " [name=" + name + ", sex=" + sex + ", age=" + age + "歲, height=" + height + "cm]"; 49 }
運行結果: