Encapsulation and Abstraction
Encapsulation:
Encapsulation is one of the fundamental principles of object-oriented programming (OOP). It refers to the bundling of data (variables) and methods that operate on that data into a single unit known as a class. Encapsulation restricts direct access to some of an object's components and prevents the accidental modification of data.
Abstraction:
Abstraction is the process of hiding the complex reality while exposing only the necessary parts. In Java, abstraction is achieved through abstract classes and interfaces. An abstract class can have abstract (unimplemented) methods, providing a blueprint for its subclasses. Interfaces define abstract methods that implementing classes must provide.
Access Modifiers (public, private, protected):
Access Modifiers:
Access modifiers define the visibility and accessibility of classes, methods, and fields in Java. There are four types of access modifiers:
public: Accessible from any class.
private: Accessible only within the same class.
protected: Accessible within the same package and subclasses.
default (no modifier): Accessible within the same package.
Encapsulation and Getters/Setters:
Encapsulation with Getters and Setters:
Encapsulation can be implemented by making the instance variables private and providing public getter and setter methods to access and modify these variables, ensuring data integrity and security.
In this example, brand
is private, so it cannot be accessed directly from outside the class. The getBrand()
method allows read access, and the setBrand(String brand)
method allows modification while controlling the access to the brand
variable.
Abstract Classes and Interfaces:
Abstract Classes:
Abstract classes are classes that cannot be instantiated and can contain abstract methods (methods without implementation). Abstract classes are useful for providing a common base for subclasses.
In this example, Shape
is an abstract class with an abstract method draw()
. Subclasses of Shape
must provide an implementation for the draw()
method.
Interfaces:
Interfaces in Java are similar to abstract classes, but they can only contain abstract methods and cannot have instance variables. Classes implement interfaces and provide implementations for all abstract methods declared in the interface.
In this example, Drawable
is an interface with an abstract method draw()
. Classes that implement the Drawable
interface must provide an implementation for the draw()
method.
Example Code:
In this example, we demonstrate encapsulation with the BankAccount
class, abstraction with the Shape
abstract class, and interfaces with the Drawable
interface. Each concept is illustrated with an example class or interface and its usage in the Main
class.
Last updated