Index
1. Encapsulation:
Encapsulation is the concept of bundling the data (variables) and methods (functions) that operate on the data into a single unit, typically a class. It restricts direct access to some of an object’s components, which is a means of preventing accidental or unauthorized interference.
In simple terms:
- Data Hiding: Encapsulation protects the internal state of an object from unwanted or incorrect modification by restricting direct access.
- Access Control: We control access through access modifiers like
private
,protected
, andpublic
.
Example:
In this example:
- The
balance
variable is private, so it can’t be accessed directly from outside the class. - We use methods like
deposit
andwithdraw
to modify the balance, ensuring that all modifications are controlled and validated.
2. Object Identity:
Object identity refers to the property that each object has a unique identity, even if two objects contain the same data. This is a core feature of OOP because each object is distinct from others in memory, regardless of whether its content (state) is the same as that of another object.
- In Java, object identity is typically represented by memory address.
- The
==
operator checks reference equality (whether two references point to the same object in memory), whereas the.equals()
method can be overridden to check logical equality (whether two objects are logically equivalent).
Example:
Even though acc1
and acc2
may have the same balance, they are two different objects in memory. Hence, acc1 == acc2
will return false
.
3. Polymorphism:
Polymorphism means “many forms.” In OOP, polymorphism allows objects of different classes to be treated as objects of a common superclass. There are two types of polymorphism in Java:
-
Compile-time polymorphism (Method Overloading): When multiple methods in the same class have the same name but different parameter lists (signature).
-
Run-time polymorphism (Method Overriding): When a subclass provides a specific implementation of a method that is already defined in its superclass. This happens through inheritance.
Method Overloading Example:
Here we can see that there are two methods with the same name double, but their signatures or parameters, datatypes are different.
Method Overriding Example:
Here we see that the class Dog, inherits the method sound from it’s parent class Animal but it changes the contents of the parent’s method with it’s own code, thus overriding the method.
This falls under inheritance which shall be further discussed in detail in module 3.