java面向对象(封装)-定义一个Dog类,类中属性有名字,年龄,性别(ture-公)

定义一个Dog类,类中属性有名字,年龄,性别(ture-公)
1.提供一个无参数的构造方法和一个带有三个参数的构造方法
2.类中定义一个无参数的play方法:输出 宠物狗
3.类中定义一个带有一个参数的play方法,参数类型为int hours,打印输出玩的小时数
4.定义一个测试类,分别用无参数的构造法和有参数的构造方法创建对象,并对属性赋值,分别
将对象的信息打印在控制台上,调用play方法
public class Dog {
   
    String name;
    int age;
    Boolean sex;
   

    public Dog() {
    }

    public Dog(String name, int age, Boolean sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    

    public void play(){
        System.out.println("宠物狗");
    }

    public void play(int hours){
        System.out.println("玩了"+hours+"小时");
    }

}

class DogTest{
    public static void main(String[] args) {
        Dog dog1 = new Dog();
        dog1.name="哈士奇";
        dog1.age=5;
        dog1.sex=true;

        Dog dog2 = new Dog("拉布拉多",4,false);

        if (dog1.sex==true){
            System.out.println("姓名:"+dog1.name+" 年龄:"+dog1.age+" 性别:公");
        }else {
            System.out.println("姓名:"+dog1.name+" 年龄:"+dog1.age+" 性别:母");
        }
        dog1.play();

        if (dog2.sex==true){
            System.out.println("姓名:"+dog2.name+" 年龄:"+dog2.age+" 性别:公");
        }else {
            System.out.println("姓名:"+dog2.name+" 年龄:"+dog2.age+" 性别:母");
        }
        dog2.play(3);

        
    }
}
对类进行封装
public class Dog {
  
    //进行封装
    private String name;
    private int age;
    private Boolean sex;

    public Dog() {
    }

    public Dog(String name, int age, Boolean sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Boolean getSex() {
        return sex;
    }

    public void setSex(Boolean sex) {
        this.sex = sex;
    }

    public void play(){
        System.out.println("宠物狗");
    }

    public void play(int hours){
        System.out.println("玩了"+hours+"小时");
    }

}

class DogTest{
    public static void main(String[] args) {
        Dog dog1 = new Dog();
      

        Dog dog2 = new Dog("拉布拉多",4,false);

       

        dog1.setName("哈士奇");
        dog1.setSex(true);
        dog1.setAge(5);

        if (dog1.getSex()==true){
            System.out.println("姓名:"+dog1.getName()+" 年龄:"+dog1.getAge()+" 性别:公");
        }else {
            System.out.println("姓名:"+dog1.getName()+" 年龄:"+dog1.getAge()+" 性别:母");
        }
        if (dog2.getSex()==true){
            System.out.println("姓名:"+dog2.getName()+" 年龄:"+dog2.getAge()+" 性别:公");
        }else {
            System.out.println("姓名:"+dog2.getName()+" 年龄:"+dog2.getAge()+" 性别:母");
        }
    }
}

你可能感兴趣的:(JavaSE基础,java,开发语言)