Wrapper methods and wrapper classes [closed]

巧了我就是萌 提交于 2020-01-03 04:36:07

问题


I am working on exam prep at the moment and I came across a question down the bottom of this post..It relates to Wrapper methods Vs Wrapper classes. Is there a difference here? As I understand that wrapper classes allow primitives to be wrapped in objects so they can be included in things like collections. Wrapper classes also have a bunch of utility methods to allows to convert to and from string objects. I have a question below that asks about wrapper methods and relates them to getter/setter methods. Am I right to think that the set wrapper method is just taking a primitive and wrapping it in an object or is it doing something different?

What are wrapper methods and when are they useful?

In the City class write the set/get wrapper methods that will allow direct access to each of its location's attributes, latitude and longitude., e.g., setLatitude:

class City {
    //...

    public void setLatitude(double value) 
    {
        location.setLat(value);
    }

    //your code:
}

回答1:


A wrapper class is a class that extends the usability of a certain class or primitive. For example take this class:

public class NewBoolean{
    private boolean value = false;
    public NewBoolean(boolean state) {
        value = state;
    }
    public boolean value() {
        return value;
    }
    public void setValue(boolean value) {
        this.value = value;
    }
    public boolean isTrue() {
        return value;
    }

    public boolean isFalse() {
        return !value;
    }

    public boolean compare(boolean anotherBoolean){
       return value==anotherBoolean;
    }
}

It can replace any boolean value, and has new methods that can extend the usability of a boolean primitive.

A wrapper method could refer to a wrapper function. Wrapper methods are just methods that call other methods, for example, we might have this two methods in a class:

public void setFullScreen() { }
public void setWindowMode() { }

And a wrapper method might be:

public void toggleFullScreen() {
    if(fullscreen) {
         setWindowMode();
    }
    else {
         setFullScreen();
    }
}

In short, a method that calls another method already inside the class. Another example woud be a setResolution(w,h); and a wrapper method what calls setDefaultResolution(), which would in turn call setResolution(DEFAULT_W,DEFAULT_H) inside.




回答2:


I heard the term 'wrapper class' being used as a synonym for a decorator class (see the 'decorator pattern') which has more usages then just allowing primitive types to be inserted into a Collection



来源:https://stackoverflow.com/questions/10563950/wrapper-methods-and-wrapper-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!