包装方法和包装类 [英] Wrapper methods and wrapper classes
问题描述
我目前正在准备考试,我在这篇文章的底部遇到了一个问题..它与包装方法与包装类有关.这里有区别吗?据我了解,包装器类允许将基元包装在对象中,以便将它们包含在诸如集合之类的东西中.包装类也有一堆实用方法,允许与字符串对象相互转换.我在下面有一个问题,询问包装方法并将它们与 getter/setter 方法相关联.我是否认为 set 包装器方法只是采用一个原语并将其包装在一个对象中,或者它正在做一些不同的事情?
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?
在 City 类中编写 set/get 包装器方法,这些方法将允许直接访问其每个位置的属性,纬度和经度.例如,setLatitude:
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:
}
推荐答案
包装类是扩展特定类或原语可用性的类.以这个类为例:
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;
}
}
它可以替换任何 boolean
值,并且具有可以扩展 boolean
原语可用性的新方法.
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() { }
包装方法可能是:
public void toggleFullScreen() {
if(fullscreen) {
setWindowMode();
}
else {
setFullScreen();
}
}
简而言之,一个调用类中已经存在的另一个方法的方法.另一个例子是一个 setResolution(w,h);
和一个调用 setDefaultResolution()
的包装方法,后者又会调用 setResolution(DEFAULT_W,DEFAULT_H)
在里面.
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.
这篇关于包装方法和包装类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!