Object Methods and Access
- Methods are the actions that an object can perform.
- They define the behaviour of an object and provide an interface for interacting with it.
In the Person class, methods like sleep, wakeUp, walk, and run define what a Person object can do.
class Person{
void sleep(){
...
}
void wakeUp(){
}
void walk(){
...
}
void run(){
}
}To utilise the benefits of OOP, we must clearly define the scope of class variables and methods, that is, specify from where they are directly accessible.
Hence, we need access modifiers.
Access modifiers
Keywords that define the visibility and accessibility of class members (variables and methods).
Access modifiers are essential for implementing encapsulation, a core principle of OOP that promotes data hiding and modular design.
We have three primary access modifiers:
Private
- Definition: Members marked as private are accessible only within the class that defines them.
- Purpose: Ensures that sensitive data and internal logic are protected from external modification.
- Java:
Here, in the ReadingMaterial class, instance variables like id, title, pages, and price are private.
class ReadingMaterial{
private int id;
private String title;
private int pages;
private double price;
public static void main(String[] args){ // to test
ReadingMaterial book = new ReadingMaterial(); // get book object
book.title = "Fahrenheit 451"; // error as you cannot access it from here
}
}The access modifier keyword is written before the data type in the declaration of the variable or method signature.
Protected
- Definition: Members marked as protected are accessible within the class, its subclasses, and classes in the same package.
- Purpose: Allows subclasses to inherit and use these members while keeping them hidden from unrelated classes.
The bookstoreName attribute in the ReadingMaterial class is protected.
class ReadingMaterial{
protected String bookstoreName;
...
}Protected access is particularly useful in inheritance hierarchies, where subclasses need to access certain members of their parent class.
Public
- Definition: Members marked as public are accessible from any class.
- Purpose: Provides an interface for interacting with the class's functionality.
Usually, classes are public.
public myClass{
...
}- Be cautious when making members public.
- Exposing too much can lead to unintended dependencies and make the codebase harder to maintain.