Alan Lam
Alan Lam

Reputation: 23

Java Object set attribute default

class AStudent {
    private String name;
    public int age;
    public void setName(String inName) {
        name = inName;
    }

    public String getName() {
        return name;
    }
}
public class TestStudent2 {
    public static void main(String s[]) {
        AStudent stud1 = new AStudent();
        AStudent stud2 = new AStudent();
        stud1.setName("Chan Tai Man");
        stud1.age = 19;
        stud2.setName("Ng Hing");
        stud2.age = -23;
        System.out.println("Student: name="+stud1.getName()+
                           ", age=" + stud1.age);
        System.out.println("Student: name="+stud2.getName()+
                           ", age=" + stud2.age);
    }
}

How can I enhance the class AStudent by adding data encapsulation to the age attribute. If the inputted age is invalid, I want to print an error message and set the age to 18.

Upvotes: 2

Views: 344

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201439

First, modify age so that it isn't public. Then add accessor and mutator methods (in the mutator, check for an invalid value - and set it to 18). Something like,

private int age;
public int getAge() {
    return age;
}
public void setAge(int age) {
    if (age < 0) {
        System.err.println("Invalid age. Defaulting to 18");
        age = 18;
    }
    this.age = age;
}

Then you could use it with something like setName

stud1.setAge(19);

and

stud2.setAge(-23);

And you could make it easier to display by overriding toString in AStudent like

@Override
public String toString() {
    return String.format("Student: name=%s, age=%d", name, age);
}

Then you can print yor AStudent instances like

System.out.println(stud1); // <-- implicitly calls stud1.toString()
System.out.println(stud2);

Upvotes: 2

krock
krock

Reputation: 29619

You are using encapsulation for the name attribute. You could do the same for age.

class AStudent {
    // ...
    private int age;
    public void setAge(int age) {
        this.age = age;
        if (age < 1) {
            this.age = age;
        }
    }
}

The above code changes the age attribute to private so that access is restricted to the getter and setter. So you will also have to add a getter method and change TestStudent2 to use the new getter and setter.

What makes an age invalid? The above code assumes any value less than 1 is invalid.

Upvotes: 0

Related Questions