It is time to begin to make the transition to using full Java objects. Java offers a number of features for object-oriented programming. In this module, we will highlight a few of the most important features. You can do more than this with objects, but this should be enough to get you started. You can read more at the Java tutorial.
Let's start with access control. There are two types of access control:
These are Java keywords use to indicate whether a method or variable can be accessed from a reference variable. A public method or variable can be accessed using the reference variable. A private one can not. Its scope is limited to the definition of the class. Let's take a look.
We do this in order to keep the interface, the methods and variables accessible from the reference variable to a minimum. Sometimes variables are only used inside the object. The should never be changed by a programmer who using instances of the object, so we hide them. As you design your objects, you want to expose only the most important details. Everything else should stay locked inside of the object.
If you set a variable to be private, it means you can't change its value. What's happens if you need to? That is what a getter and setter is for. A getter / setter is a public method for changing the value of a private variable.
It might seem a little clumsy to use a getter / setter at first, but the power comes in when you want to do something special like storing the radius in addition to its diameter.
An interface is a description of what an implementing object can do. It like the buttons on a controller. It is a list of methods. It does not include any implementation. We use interfaces to describe the possible behaviours of all the implementing objects. An object can implement multiple interfaces.
There are two different kinds of methods:
A class method is a method that is defined one and stored in memory only once for every instance of the object created. An instance method is a method that has a copy stored in memory for each instance of the object.
A variable can also be static. It means that all instances of the class share the variable.
A variable can also be declared final. This means that it will never change. We often tell Java that a variable is a constant by declaring that it is both static and final.