你的位置:首页 > Java教程

[Java教程]Java类和对象8


按要求编写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   @Override47   public String toString() {48     return " [name=" + name + ", sex=" + sex + ", age=" + age + "岁, height=" + height + "cm]";49   }

运行结果: