Objects are all around us; the monitor your looking at, your IPod, your cat or dog, etc. Programming objects mimic those found in real life. When you use an object, like an IPod, there are certain things you can do with it. The object has an Interface, or way for you to interact with the object. The object also has properties that work internally that you do not have direct access to, such as the current song playing, the next song to play, the current play position, etc.
Programming Objects store the state of an Object in internal variables and has methods that are used to access that information.
Access modifiers let you set the access level of class properties or functions.
- Private – Only this class’ functions can use the item.
- Public – This class’ functions and any outside source can use the item.
- Protected – This class or any Child Class can use the item.
In Object-Oriented Programming, your Class files have internal data members, or variables. These variables hold properties of the Object. By setting your Class variables to Private or Protected, you ensure that anyone using your Class cannot access the data directly. If the variable needs to be accessed outside the Class, then Get or Set functions can be setup to allow access. This ensures that your Class’ data cannot be changed without your knowledge. This is called Encapsulation and allows for Data Hiding.
Imagine a radio Object in the example on the right-side where the two Class variables (in green) are Encapsulated in the object and surrounded by the Public Interface (in blue) to those variables.
One of the benefits of using Get and Set functions to access your Class variables is that you can do some validation to make sure the data is valid before storing it.
Each object, or Class file, you create will have a Public Interface that allows your program, or other classes, to communicate with it. By using the Public access modifier, you allow anyone who creates an instance of your Class to access that Class variable or function.
Advantages of Object Oriented Programming
- OOP creates a natural structure to your code mimicking real-world examples we can see.
- Code that deals with an Object is grouped together making it easier to reuse and maintain.
- Encapsulation allows for greater control over what variables can store.