21-案例分析三(Dog)

2020-10-30  本文已影响0人  c88bc9f9d088

案例分析三:
    设计一个Dog类,有名字,颜色,年龄等属性,定义构造方法来初始化类的这些属性,定义输出Dog信息,编写应用程序使用Dog类。

class Dog{
    private String name;  //狗的名字
    private String color;   //狗的颜色
    private int age;          //狗的年纪
    
    public Dog() {} //无参构造方法 必须有
    public Dog(String name,String color,int age) {   //三参构造
        this.name = name;
        this.color = color;
        this.age = age;
    }
    public String getInfo() {
        return "狗的名字:" + this.name + "、狗的颜色:"+ this.color + "、狗的年龄:" + this.age;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    public String getName() {
        return this.name;
    }
    public String getColor() {
        return this.color;
    }
    public int getAge() {
        return this.age;
    }
}
public class JavaDemo{
    public static void main(String args[]){
        Dog dog = new Dog("小布丁","米色",10);  //类的声明
        System.out.println(dog.getInfo());
        
    }   
}
上一篇下一篇

猜你喜欢

热点阅读