0
点赞
收藏
分享

微信扫一扫

Java面向对象 封装

朱小落 2022-03-12 阅读 61
linqc#
  1. 定义类的时候需要包含一下组件:

  2. 私有属性

  3. 构造方法(无参构造方法和自定义构造方法)

  4. set/get方法

  5. 普通方法

public class Dog {
 
   private String name;
   private int age;//私有属性,只能在当前类中调用
   private int weight;
    //构造器
    public Dog(){
 
    }
 
    //全参构造器
    public Dog(String name,int age, int weight){
        this.name=name;
        this.age=age;
        this.weight=weight;
 
    }
    //定义一个设置年龄的方法
    public void setAge(int age){
        if(age>=0){
            this.age=age;
        }else{
            System.out.println("您输入的年龄不对");
        }
    }
 
    //定义一个获取年龄的方法
    public int getAge(){
        return this.age;
    }
 
    public String getName(){
        return name;
    }
   public void setName(String name){
        this.name=name;
   }
    public int getWeight(){
        return weight;
    }
    public void setWeight(int weight){
        this.weight=weight;
    }
    //方法
    public void eat(){
        System.out.println("eating bones");
    }
    public void play(){
        System.out.println("playing...");
    }
    public void show(){
        System.out.println("name:"+this.name);
        System.out.println("age:"+this.age);
        System.out.println("weight:"+this.weight);
    }
}

举报

相关推荐

0 条评论