简体   繁体   English

Java 对象设置属性默认值

[英]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.如何通过向age属性添加数据封装来增强类AStudent If the inputted age is invalid, I want to print an error message and set the age to 18.如果输入的age无效,我想打印错误信息并将年龄设置为18。

First, modify age so that it isn't public.首先,修改age ,使其不公开。 Then add accessor and mutator methods (in the mutator, check for an invalid value - and set it to 18).然后添加访问器和修改器方法(在修改器中,检查无效值 - 并将其设置为 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然后你可以将它与setName东西一起使用

stud1.setAge(19);

and

stud2.setAge(-23);

And you could make it easier to display by overriding toString in AStudent like您可以通过在AStudent覆盖toString来使其更容易显示,例如

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

Then you can print yor AStudent instances like然后你可以打印你的AStudent实例,比如

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

You are using encapsulation for the name attribute.您正在对name属性使用封装。 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.上面的代码将age属性更改为private,以便访问仅限于getter 和setter。 So you will also have to add a getter method and change TestStudent2 to use the new getter and setter.因此,您还必须添加一个 getter 方法并更改TestStudent2以使用新的 getter 和 setter。

What makes an age invalid?什么使年龄无效? The above code assumes any value less than 1 is invalid.上面的代码假定任何小于 1 的值都是无效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM