zoukankan      html  css  js  c++  java
  • 封装

     意义 

       我们程序设计要追求“高内聚,低耦合”。高内聚就是类的内部数据操作细节自己完成,不允许外部干涉;低耦合:仅暴露少量的方法给外部使用

        便于调用者调用。

        良好的封装,便于修改内部代码,提高可维护性。

        良好的封装,可进行数据完整性检测,保证数据的有效性。

    使用访问控制符,实现封装 

    同一个类

    同一个包中

    子类

    所有类

    private

    *

    default(即不加修饰符的时候)

    *

    *

    protected

    *

    *

    *

    public

    *

    *

    *

    *

      1.属性一般使用private.(除非本属性确定会让子类继承并且使用)
        提供相应的get/set方法来访问相关属性. 这些方法通常是public,从而提供对属性的读取操作。  (注意:boolean变量的get方法是用:is开头!)
      2.一些只用于本类的辅助性方法可以用private,希望其他类调用的方法用public。

        package cn.bjsxt.oop.encapsulation01;
     
    public class Man {
        private String name;
        private String id;
        private boolean man;
        public static int cc;
        public static final int MAX_SPEED = 120;
        public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public boolean isMan() {
        return man;
    }
    public void setMan(boolean man) {
        this.man = man;
    }
    }
    

      

    package cn.bjsxt.oop.encapsulation01;
     public class Test01 {
        private String str;
    protected void print(){
        String s = str;
        System.out.println("Test01.print()");
    }
    }
     
    class Test001 extends Test01 {
        public void pp(){
        super.print();
    }
    public static void main(String[] args) {
        Test01 t = new Test01();
        t.print();
    }
    }
     
    package cn.bjsxt.oop.encapsulation01;
     
    public class Test02 {
    public static void main(String[] args) {
        Test01 t = new Test01();
        t.print();
    }
    }
    package cn.bjsxt.oop.encapsulation02;
     import cn.bjsxt.oop.encapsulation01.Test01;
     public class Test0001 extends Test01 {
        public void ttt(){
        super.print();
        print();
    }
    public static void main(String[] args) {
        Test0001 t = new Test0001();
        t.print();
    }
    }
     
    package cn.bjsxt.oop.encapsulation02;
     import cn.bjsxt.oop.encapsulation01.Test01;
     
    public class Test03 {
    public static void main(String[] args) {
        Test01 t = new Test01();
        //  t.print();
    }
    }
     
    

      

  • 相关阅读:
    20110603 本日跌的股票之后一段时间轻易不要碰
    一日三省
    火电排污新标准年内出台 撬动千亿脱硝市场
    20082011大股东增持专题
    收评:5月24日资金流向(摘自益盟)
    2011年中期业绩预增前20家公司
    2011大股东十大增持概念股全景图
    放不下期货
    从众是通向地狱最廉价的门票
    在ASP.NET中获取Get方式和Post方式提交的数据
  • 原文地址:https://www.cnblogs.com/zqy6666/p/12053694.html
Copyright © 2011-2022 走看看