美文网首页
wrapper class

wrapper class

作者: Wilbur_ | 来源:发表于2020-04-25 00:12 被阅读0次

今天学到了wrapper class,其实本质上就是把当前的object当作argument,然后在目前的constructor上面重新建立一个一样的object,然后改他的各种 method,从而达到能够修改想要不同output的目的,比如

public class Solution {

    public class TableInterfaceWrapper implements TableInterface {
        TableInterface tableInterface1;
        public TableInterfaceWrapper(TableInterface tableInterface) {
            this.tableInterface1 = tableInterface;
        }

        @Override
        public void setModel(List rows) {
            System.out.println(rows.size());
            tableInterface1.setModel(rows);
        }

        @Override
        public String getHeaderText() {
            return this.tableInterface1.getHeaderText().toUpperCase();
        }

        @Override
        public void setHeaderText(String newHeaderText) {
            this.tableInterface1.setHeaderText(newHeaderText);
        }
    }

    public interface TableInterface {
        void setModel(List rows);

        String getHeaderText();

        void setHeaderText(String newHeaderText);
    }

    public static void main(String[] args) {
    }
}

这里面

        TableInterface tableInterface1;
        public TableInterfaceWrapper(TableInterface tableInterface) {
            this.tableInterface1 = tableInterface;
        }

TableInterface tableInterface1; 就是先弄了一个新的variable,然后在

public TableInterfaceWrapper(TableInterface tableInterface) {
            this.tableInterface1 = tableInterface;
        } 

这一段里用原本的TableInterface 作为object的type,然后新建立一个当前class里面的tableinterface,然后就可以用它来修改自己想要的数据了。
最直观了当的例子就是Integer class 实际上就是wrapper class,它是把primitive type int 包起来,然后可以建立很多新的method,比如

image.png
这张图片里就能让我们很清楚的看到各种已经可以调用的method,比如找出两个数里面谁最大,把一个string转换成int,等等等等。这样其实就很方便了,因为原始type(primitive type)并没有这些功能,你用wrapper把int包裹起来以后就可以做很多事情了,而且它兼容所有的int,不用担心出问题。

相关文章

  • wrapper class

    今天学到了wrapper class,其实本质上就是把当前的object当作argument,然后在目前的cons...

  • Java-装箱拆箱

    包装类(Wrapper Class) 八个和基本数据类型对应的类统称为包装类(Wrapper Class) 包装类...

  • 朱文倩进度条