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();
    }
    }
     
    

      

  • 相关阅读:
    jQuery让渡$操作符
    JSON
    Jquery实现Ajax(二)
    Jquery实现Ajax(一)
    Javascript实现Ajax
    文章目录
    读过的书
    JVM笔记(5)-垃圾回收&内存分配策略
    JVM笔记(4)-对象及其引用
    JVM笔记(3)-内存结构&方法执行(栈帧)
  • 原文地址:https://www.cnblogs.com/zqy6666/p/12053694.html
Copyright © 2011-2022 走看看