Object-Oriented Programming Core Concepts
Object-oriented programming (OOP) is a programming paradigm that organizes code around the concept of "objects", which are instances of classes that encapsulate data and procedures. OOP promotes concept such as encapsulation, inheritance, and polymorphism, making code more modular, reusable, and flexible for easier management of complex systems. In this post, we are going to explore the key concepts used in OOP.
Object
-
Real-word objects
- Everything arounds you, exists in nature
- Share 2 characteristics: State And Behavior
- Example:
- Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail)
- Bicycles have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes)
-
Software objects
- Conceptually similar to Real-world objects
- Consist of state and related behavior
- An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages)
- Objects communication: methods of objects operate on an object's internal state (such as get(), set() method) and serve as the primary mechanism for object-to-object communication --> The action of hiding internal state and requiring all objects' interactions to be performed through an object's methods - known as "Data Encapsulation" - a fundamental principle of object-oriented programming
- A software object overview
- A software bicycle object example:
-
Benefits of organizing code into separate software objects offers numerous benefits
- Modularity: allows for independent development and integration of object code
- Information-hiding: ensures that internal implementation details are kept private
- Core re-use: permits the utilization of pre-existing objects in new programs, enhancing efficiency and reliability when implement/test/debug, task-specific objects.
- Pluggability & Debugging ease: facilitate the removal and replacement of problematic objects without affecting the entire system, akin to fixing mechanical components in the real world.
-
Reference: 🍎 Objects
Class
-
Given the situation: in the real world, it is common to come across multiple individual objects of the same kind.
- For example, there may be thousands of other bicycles in existence, all of the same make and model - Each bicycle was built from the same set of blueprints and therefore contains the same components.
- --> In object-oriented terms, your bicycle is an instance of the class of objects known as bicycles.
-
==> A class is the blueprint from which individual objects are created.
-
class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changeCadence(int newValue) { cadence = newValue; } void changeGear(int newValue) { gear = newValue; } void speedUp(int increment) { speed = speed + increment; } void applyBrakes(int decrement) { speed = speed - decrement; } void printStates() { System.out.println("cadence:" + cadence + " speed:" + speed + " gear:" + gear); } }
-
The Bicycle class here is the blueprint which is used in the application - it means that some other class in your application will use this blueprint to new Bicycle objects.
- For example, a BicycleDemo class creates two seperate Bicyle objects and invokes their methods:
class BicycleDemo { public static void main(String[] args) { // Create two different // Bicycle objects Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); // Invoke methods on // those objects bike1.changeCadence(50); bike1.speedUp(10); bike1.changeGear(2); bike1.printStates(); bike2.changeCadence(50); bike2.speedUp(10); bike2.changeGear(2); bike2.changeCadence(40); bike2.speedUp(10); bike2.changeGear(3); bike2.printStates(); } }
-
Reference: 🍎 Classes
Inheritance
- Given the situation: Different types of objects frequently share similarities or characteristics with one another.
- For example:
- Mountain bikes, road bikes, and tandem bikes -- these all share the characteristics of bicycles (current speed, current pedal cadence, current gear)
- --> But problem here, that is although they have many in commons but each kind of them defines additional features that make them different:
- tandem bicycles have two seats and two sets of handlebars
- road bikes have drop handlebars
- some mountain bikes have an additional chain ring, giving them a lower gear ratio
- For example:
- Resolves problem: Object-oriented programming allows classes to inherit commonly used state and behavior from other classes
- For example,
Bicycle
now becomes the superclass ofMountainBike
,RoadBike
, andTandemBike
- For example,
In the Java programming language, EACH CLASS IS ALLOWED TO HAVE ONE DIRECT SUPERCLASS. But each superclass has the potential for an unlimited number of subclasses
- The syntax for creating a subclass example:
class MountainBike **extends** Bicycle {
// new fields and methods defining
// a mountain bike would go here
}
//This gives `MountainBike` all the same fields and methods as `Bicycle`, yet allows its code to focus exclusively on the features that make it unique
- Reference:
Interface
-
As we have already mentioned, objects communicate with the outside world through the methods that they expose.
-
Methods serve as the means with the external environment.
- For example, the buttons on the front of your TV set - are the interface between you and the electrical wiring on the other side of its plastic casing --> If you press the "power button" --> the television turns on or off.
-
The interface typical form is a collection of related methods that do not have any implementation details == methods with empty body.
- For example, describe bicycle's behavior as an interface:
interface Bicycle { // wheel revolutions per minute void changeCadence(int newValue); void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); }
- A new class will implement this interface using the
implements
keyword. The implemented classes of this interface must override the methods defined in the interface.
class ACMEBicycle **implements** Bicycle { int cadence = 0; int speed = 0; int gear = 1; // The compiler will now require that methods // changeCadence, changeGear, speedUp, and applyBrakes // all be implemented. Compilation will fail if those // methods are missing from this class. void changeCadence(int newValue) { cadence = newValue; } void changeGear(int newValue) { gear = newValue; } void speedUp(int increment) { speed = speed + increment; } void applyBrakes(int decrement) { speed = speed - decrement; } void printStates() { System.out.println("cadence:" + cadence + " speed:" + speed + " gear:" + gear); } }
-
The powerful of implementing Interface
- Implementing an interface allows a class to become more formal about the behavior it promises to provide.
- Interfaces form a contract between the class and the outside world. This contract is enforced at build time by the compiler --> If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
-
Reference: 🍎 Interfaces
-
A package - a namespace that organizes a set of related classes and interfaces.
- Similar to your different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another for example.
-
The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications.
- This library is known as the "Application Programming Interface", or "API" for short
- Developers can create their own libraries and compress as file jar for reusing across java software projects.
- In Java, there are two types of packages: built-in packages and user-defined packages.
- Built-in Packages: predefined packages known as standard packages of the Java Development Kit (JDK), support a wide range of classes and interfaces for various purpose.
- Some commonly used built-in packages include:
java.lang
,java.util
,java.io
and so on.
- Some commonly used built-in packages include:
- User-defined packages: packages created by Java developers to organize their classes and resources, improving code organization, readability, and maintainability.
- Built-in Packages: predefined packages known as standard packages of the Java Development Kit (JDK), support a wide range of classes and interfaces for various purpose.
- Its packages represent the tasks most commonly associated with general-purpose programming.
- For example:
- a
String
object contains state and behavior for character strings; - a
File
object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem;
- a
- For example:
- Reference: 🍎 Packages
- This library is known as the "Application Programming Interface", or "API" for short