【Java】設計一個包含多個構造函數的類,並分別用這些構造函數來進行實例化對象。


class Person {
    private String name;
    private int age;

    // 默認構造函數; 構造對象
    public Person() {
        this.name = "易烊千璽";
        this.age = 19;
    }

    //帶有兩個參數的構造函數
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void eat() {
        System.out.println(this.name + "吃飯!");
    }

    public void sleep() {
        System.out.println(this.name + "睡覺!");
    }

    public void show() {
        System.out.println("name: " + name + " age: " + age);
    }
}

public class Test2 {
    public static void main(String[] args) {
        Person person = new Person();
        Person person1 = new Person("小余",20);
        Person person2= new Person("小張",19);
        person1.eat();
        person2.sleep();
        person.show();
        person1.show();
    }
}

運行結果如下
在這裏插入圖片描述

發佈了34 篇原創文章 · 獲贊 29 · 訪問量 3689
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章