封装

 

封装:将类的某些信息隐藏在类内部,不允许外部程序直接访问,而是通过该类提供的方法来实现对隐藏信息的操作和访问。

 

    封装的步骤

 

    [1]属性私有化

 

    [2]提供公共的设置器和访问器

 

    [3]在设置器和访问器中添加业务校验逻辑

public class Dog{
    
    // 【1】private 私有的,对外不可见
    private String name;
    private int health;
    private int love;
    private String strain;

    // 【2】提供公共的设置器(setter)和访问器(getter)
    public void setName(String name){
        // 【3】逻辑校验
        if(name.equals("")){
            System.out.println("姓名不能为空.");
        }else{
            this.name = name;
        }
    }
    public String getName(){
        return this.name;
    }
    
    public void setHealth(int health){
        if(health < 0){
            System.out.println("健康值不合法.");
            this.health = 0;
        }else{
            this.health = health;
        }
    }
    public int getHealth(){
        return this.health;
    }
    
    public void setLove(int love){
        if(love < 0){
            System.out.println("亲密度不合法.");
            this.love = 0;
        }else{
            this.love = love;
        }
    }
    public int getLove(){
        return this.love;
    }
    
    public void setStrain(String strain){
        if(strain.equals("")){
            System.out.println("品种不能为空.");
        }else{
            this.strain = strain;
        }
    }
    public String getStrain(){
        return this.strain;
    }
    
    
    public Dog(){
        
    }

    public Dog(String name,int health,int love,String strain){
        this.setName(name);
        this.setHealth(health);
        this.setLove(love);
        this.setStrain(strain);
    }
    
    public void showInfo(){
        System.out.print("我的名字叫"+this.name);
        System.out.print(",健康值"+this.health);
        System.out.print(",亲密度"+this.love);
        System.out.println(",我是一只"+this.strain);
    }
}

 

 

构造器

  无参构造器

  1. 无参构造方法就是构造方法没有任何参数。构造方法在创建对象(new Dog())调用,无参构造方法中一般用于给属性赋值默认值。
  2. 如果开发中没有定义无参构造方法,jvm默认给类分配一个无参构造,形如

  有参构造器

  1. 当构造/实例化一个对象时,可以向构造方法中传递参数,这样的构造方法称为有参构造

 

This关键字(上)

    注意:this调用其他构造方法必须写到构造方法的第一句。

     对象初始化内存图

 

 

 

this 是一个关键字,表示对象本身,本质上this中存有一个引用,引用对象本身。

this用于访问本对象属性,同时解决局部变量和成员变量同名的问题。

 

 

  方法的调用内存图

this表示对象本身。

[1] this调用属性

[2] this调用方法

 

posted on 2019-04-20 21:41  德德玛  阅读(105)  评论(0编辑  收藏  举报