Java類和對象8,Java類對象8

來源:互聯網
上載者:User

Java類和對象8,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     }

運行結果:

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.