I'm doing a Java assignment in Greenfoot and I'm stuck on a question about getter and setter methods which I cannot find an answer to.
I'm asked to write a getter and setter method for three attributes (name, colour, age) and then use these methods to:
(a) ensure that age cannot be less than 0 and age cannot be greater than 100
(b) ensure the only valid colours are Black, White, Brown and Grey
Any ideas or suggestions to how I would solve this problem?
Thanks in advance
I hope that help you, that will give you at least a visibility and you can modify it as you want :
public class MyClass {
private String name;
private int age;
private String color;
private final List<String> colors = Arrays.asList("Black", "White", "Brown ", "Grey");
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
if (colors.contains(color)) {
this.color = color;
} else {
// if not valid do what you want
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 0 && age <= 100) {
this.age = age;
} else {
// if not valid do what you want
}
}
}