Issue
public class Person {
String name;
int year;
int month;
int day;
String email;
String phonenr;
public Person(String name, int year, int month, int day, String email, String phonenr) {
this.name = name;
this.year = year;
this.month = month;
this.day = day;
this.email = email;
this.phonenr = phonenr;
}
I have this object. I want to access email atribute only in another class so i could check if the email is valid using assert in test directory. How do I access only email atribute from Person in another class to use it later to validate the email?
This is the class i want to access email atribute from.
public class PersonValidator {
public static boolean email(String email){
Person onePerson = new Person();
return false;
}
}
This is test class to test if email is valid:
class PersonRegisterTest {
@Test
void checkValidEmail() {
assertTrue(PersonValidator.email("[email protected]"));
assertTrue(PersonValidator.email("[email protected]"));
assertTrue(PersonValidator.email("[email protected]"));
}
Solution
Good practice in Java is to make all fields private
, and create "getters and setters", i.e. functions to get and set values. For example:
public class Person {
private String email;
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return this.email;
}
}
This way of doing things has several advantages:
If you you decide you want to change what values are allowed in a field, you can do that using the setter method. For example, if you want to impose a minimum length on emails, you can put
if (email.length() < 10) return;
in your method to prevent emails shorter than 10 charactersIf you decide you want to retrieve emails over the internet or some other way, you do not have to change your code.
Many tools and frameworks expect Java objects to be in this format. Notable examples include Jackson for JSON serialization, and Spring/Spring Boot, for web application development, as well as many many more.
P.S. if you are sick of writing getters and setters:
- Check if your IDE has a way of automatically generating them (most of them do)
- Look into a library called Lombok, it provides the
@Data
annotation which can generate these methods automatically at compile time. (https://projectlombok.org/)
Answered By - cameron1024
Answer Checked By - Timothy Miller (JavaFixing Admin)