不会拐弯的小树苗 2022-04-25 21:29 采纳率: 90%
浏览 30
已结题

请问类可以全面改变数据存储方式在这段话是什么意思呢

img


详情问题请参考题目,感谢热心群众的解答。封装怎么会扯到类改变数据存储方式呢

  • 写回答

2条回答 默认 最新

  • 宁-静-致-远 2022-04-25 23:36
    关注

    这句话主要讲的是封装的意义,当你设计好一个类后。类内部封装的方法或者数据域(私有非公开的),类的设计者是可以变更这些方法的实现或者数据域的类型、赋值方式等。只要不修改公开的方法那么就不会影响到使用该类的其它类。
    比如:

    public class t {
        //使用一个固定长度的数组存放数据(私有)
        private Integer [] numbers = new Integer[100];
        private int index = 0;
        private int index1 = 0;
        /**
         * 将数据存储至数组中(公共)
         * @param num
         */
        public void add(Integer num){
            numbers[index] = num;
            index ++;
        }
    
        /**
         * 获取一个数据(公共)
         * @return
         */
        public Integer next(){
            if( index1 >= index) {
                index1 = 0;
            }
            Integer t = numbers[index1];
            index1 ++;
            return t;
    
        }
    
        public static void main(String[] args) {
            //使用t进行数据存储
            t t1 = new t();
            t1.add(1);
            t1.add(2);
        }
    }
    

    发现问题,调整类的具体实现

    public class t {
        //使用一个固定长度的数组存放数据(私有)
        //private Integer [] numbers = new Integer[100];
        //后期发现正常使用过程中经常出线超出数组长度的问题,为了解决该问题我使用了List对象,
        //因为原有数据域数组是私有的(封装的特性),那么我就可以肯定别人在使用该类的时候肯定是不可能直接访问到的,那么我就可以直接按需要使用List对象替换原有的数组类型
        private List<Integer> numbers = new ArrayList<>();
        private int index1 = 0;
        /**
         * 将数据存储至数组中(公共)
         * @param num
         */
        public void add(Integer num){
            //numbers[index] = num;
            //调整一下存储方式
            numbers.add(num);
        }
    
        /**
         * 获取一个数据(公共)
         * @return
         */
        public Integer next(){
            //调整一下获取下一个数据的方式
            if( index1 >= numbers.size()) {
                index1 = 0;
            }
            Integer t = numbers.get(index1);
            index1 ++;
            return t;
    
        }
    
        public static void main(String[] args) {
            //调用没有变,类的功能也没有变,只是变更了类内部的具体实现
            t t1 = new t();
            t1.add(1);
            t1.add(2);
        }
    }
    
    

    如有帮助请采纳!!!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 5月3日
  • 已采纳回答 4月25日
  • 创建了问题 4月25日