I was taught to right a class with writing all accessor and mutator methods for all its attributes. But I remember sometime (also tested and this works) dot notation is used following its attribute to access it instead of using accessor method.
public class Person
private String name;
private int age;
name = "";
age = 0;
public String getName()
public int getAge()
public void setName(String name)
this.name = name;
public void setAge(int age)
this.age = age;
Person p1 = new Person();
Now if I want to get p1's name, I can do either one:
String oldMan = p1.name;
oldMan = p1.getName();
I don't know if there is any differences between these two methods to access an attribute of an object. I was taught to create and use accessor method instead of dot notation. But the dot notation is neat.
This is really basic but sometime I forget.
Thank you for your help.
Since the fields are private, you can only do p1.name inside the same class file. If, however, you instantiated a Person in a class named "Main", then it would not work, because you wold be trying to access a private field from a different class (which is not allowed).
For this reason, accessors / mutators are used as a way to keep the implementation separated from the interface. Additionally, if you had placed checks (e.g. age must be positive), you could either throw an exception or set a default value when someone called person.setAge(0). You cannot add such constraints on the statement person.age = 0;
That makes sense now. I had everything in one file, that's why it works.