新手求助-有关信息隐藏
各位高手,小弟有个问题想请教一下。
在Student类里有Bag类型的成员(bag),我想做以下功能
新建一个学生类的对象(aStudent)之后的第一次对该aStudent的成员bag赋值,
之后不让其它语句修改aStudent的成员bag;
Student类和Bag类在下面。麻烦各位帮我看看能不能达到这个效果,或者有其它更好的方法。
package learning.myclazz;
public class Student {
private String name;
private int age;
private Bag bag;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Bag getBag() {
try {
return bag.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
public void setBag(Bag bag) {
if (this.bag == null) {
this.bag = bag;
}
}
public Student() {
name = "mike";
age = 12;
}
public void write() {
System.out.println("My name is " + name);
System.out.println("I'm " + age + " years old!");
}
}
package learning.myclazz;
public class Bag implements Cloneable {
private String bagColor;
private double bagWeight;
public String getBagColor() {
return bagColor;
}
public void setBagColor(String bagColor) {
this.bagColor = bagColor;
}
public double getBagWeight() {
return bagWeight;
}
public void setBagWeight(double weight) {
this.bagWeight = weight;
}
public Bag() {
this.bagColor = "yellow";
this.bagWeight = 500.00;
}
public Bag(String bagColor, double bagWeight) {
this.bagColor = bagColor;
this.bagWeight = bagWeight;
}
@Override
protected Bag clone() throws CloneNotSupportedException {
return (Bag) super.clone();
}
public void write() {
System.out.println("A bag . Color :" + this.bagColor);
System.out.println("Weight: " + this.bagWeight);
}
}