Object-Oriented Programming (OOP)
What is OOP?
OOP (Object-Oriented Programming) is a way of looking at a software system as a collection of interactive objects.
Objects
Objects represents an entity.
- Physical entity: e.g. Car
- Conceptual entity: e.g. Bank account
- Software entity: e.g. Linked List
Classes
Class is the blueprint or template of objects.
- Attributes: states, properties, etc.
- Methods: ways to interact with the object
OOP concepts
Encapsulation
Encapsulation is bundling non-visible attributes/methods with read/write methods to them.
It's usually implemented using access modifiers(public/private), setters, and getters.
- Abstraction: Hide unnecessary details
- Defensive Programming: Protect data from misuse by the outside world
Inheritance
Inheritance is making specialization and extension from existing modules/systems.
Is-a relationship indicates inheritance.
Has-a relationship indicates composition.
- Modularity: Can provide extended/modified functionality without breaking old methods (Can adopt a much more incremental approach!)
- Resuability: Can create new class from existing class
- Timeliness: Faster development time
- Reliability: Existing class has testing & validations
- Consistency: A strict emphasis on regular, coherent design
Circle-Ellipse Problem
1 | class Ellipse{ |
Circle is an Ellipse, but Circle.stretchX loses its characteristic as a circle!
OOP is not the best way...
Interface and Abstract class (in Java)
Interface and abstract class can have abstract method - method without body.
Interface can have multiple inheritance, but can't extend classes.
Abstract class can extend class and implement inheritance.
Interface provides a common interface between several unrelated classes.
Abstract class provides a blueprint for closely related classes.
Polymorphism
Polymorphism provides a way to perform a single action (with the same name) in different ways.
Overloading
Class can have two or more methods with same name but different signatures!
Overriding
Subclass can redefine an inherited instance method!
Hiding (not polymorphism)
Subclass can hide superclass's static method, static variable, instance variable.
Overridden method can't be accessed by casting to superclass, but hidden method/variable can be accessed by casting to superclass.