Working with Objects
Estimated time to read: 1 minute
Overview¶
Once an object has been created, we can work with its attributes / data and methods. Java uses a period .
to create these statements and expressions.
For example, to set racerX's gasoline attribute to 12:
The above example modifies a public field within the racerX object, normally, this data would be modified within a get/set method.
Main is special¶
Having a Main() method within a class makes it part of the overall class. This means that Main() can access data that has had its accessibility set to private.
To counter this, Main() is often moved into a separate program so that it is not part of the class and doesn't bypass any explicit bypass modifiers.
Working with an Object¶
To work with an object, it must first be instantiated. It can then be manipulated by its methods.
Example:
Car racerX = new Car(); // Object instantiation using Constructor
if(racerX.getGasoline()) <2){
racerX.setGasoline(12);
}
Just looking at the above example, it is impossible to tell what the accessibility of the methods are as the context of the method and class are unknown.
For the most part, it is safe to assume that getters and setters are public
. Having these publicly accessible is a good programming practise, as logic can be applied before a value is set, and also enables code reusability.