黑马程序员技术交流社区
标题:
代码疑问
[打印本页]
作者:
实战造就实力
时间:
2014-1-5 14:22
标题:
代码疑问
存在一个JavaBean,它包含以下几种可能的属性:
1:boolean/Boolean
2:int/Integer
3:String
4:double/Double
属性名未知,现在要给这些属性设置默认值,以下是要求的默认值:
String类型的默认值为字符串 www.itheima.com
int/Integer类型的默认值为100
boolean/Boolean类型的默认值为true
double/Double的默认值为0.01D.
只需要设置带有getXxx/isXxx/setXxx方法的属性,非JavaBean属性不设置,请用代码实现
这道题我建了两个类:
第一个类中写
package thirty;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class Test8 {
public static void main(final String[] args) {
final XBean bean = new XBean();
bean.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
System.out.println(evt);
}
});
bean.setAmount(200);
bean.setValidated(false);
bean.setSite("bbs.csdn.net");
bean.setPrice(10.11);
}
}
第二个类中写:
package thirty;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public final class XBean {
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private String site = "www.csdn.net";
private boolean validated = true;
private int amount = 100;
private double price = 0.01;
public XBean() {
}
public final String getSite() {
return site;
}
public final void setSite(final String site) {
pcs.firePropertyChange("site", getSite(), site);
this.site = site;
}
public final boolean isValidated() {
return validated;
}
public final void setValidated(final boolean validated) {
pcs.firePropertyChange("validate", isValidated(), validated);
this.validated = validated;
}
public final int getAmount() {
return amount;
}
public final void setAmount(final int amount) {
pcs.firePropertyChange("amount", getAmount(), amount);
this.amount = amount;
}
public final double getPrice() {
return price;
}
public final void setPrice(final double price) {
pcs.firePropertyChange("price", getPrice(), price);
this.price = price;
}
public void addPropertyChangeListener(final PropertyChangeListener l) {
pcs.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(final PropertyChangeListener l) {
pcs.removePropertyChangeListener(l);
}
}
运行结果为:
java.beans.PropertyChangeEvent[source=thirty.XBean@525483cd]
java.beans.PropertyChangeEvent[source=thirty.XBean@525483cd]
java.beans.PropertyChangeEvent[source=thirty.XBean@525483cd]
java.beans.PropertyChangeEvent[source=thirty.XBean@525483cd]
请问这样对吗?
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2