封装

来源:互联网 发布:软件功能过期怎么办 编辑:程序博客网 时间:2024/06/07 02:57

封装:
最常用:
将属性私有化—>使用private属性(例如年龄)
提供公共的方法以供访问;

    提高了安全性    便于调用(逻辑严谨)    提高了代码的复用性;    方法、类也是封装    将实现的细节隐藏起来,不对外直接提供    访问通过对外提供的公共路径    定义类:        将属性私有化:使用private修饰        对外提供方法:set和get方法        为了方便在创建对象时赋值,提供全参的构造方法        为了方便创建对象:提供无参的构造方法

封装:
将属性私有
提供公共方法以供访问;

    只要将细节隐藏,就是封装    方法,类----> 封装的一种方式    作用:        提高了安全性,便于调用        提高了代码复用性    

Demo

package com.niu.demo2;public class Employee {    //降属性私有化private修饰    private String name;    private String employee;    private int salary;    //无参构造    public Employee(){    }    //有参构造    public Employee(String name,String employee,int salary){        this.name = name;        this.employee = employee;        this.salary = salary;    }    //方法    public void info(){        System.out.println("姓名:"+name+"     职位:"+employee+"     薪资:"+salary);    }//set   get  方法    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getEmployee() {        return employee;    }    public void setEmployee(String employee) {        this.employee = employee;    }    public int getSalary() {        return salary;    }    public void setSalary(int salary) {        this.salary = salary;    }   }package com.niu.demo2;public class Test {    public static void main(String[] args) {                Employee emp = new Employee();        emp.setEmployee("emp");        emp.setName("tom");        emp.setSalary(1000);        emp.info();    }}
0 0
原创粉丝点击