“From Objects to Code: A Beginner’s Guide to OOP”
We’ve four main concepts in OOP:
- Encapsulation
- Abstraction
- inheritance
- polymorphism
In this article, I’ll give you real-life examples and teach you how to implement each of these concepts.
Finally, I’ll show a small app that implements all of these concepts.
Prerequisites: I will use basic java code to demonstrate the idea, So I assume you have a basic idea about java and what is an object and class in programming, See this crash course before reading the article.
Encapsulation
What is “Encapsulation” and how to implement it?
Real-life example
When we have a book, a pen, and an eraser and put all of them inside the bag, This means that we’ve encapsulated these school supplies inside the bag.
But our bag is open, We should close it so no one messes with it and no one of it is lost.
Do not keep your bag open.
In programming when we combine variables and methods in one unit, this is called encapsulation, But weak encapsulation, Recall the real-life example above when I said “do not keep your bag open”, The same concept applied here, we should make a strong encapsulation by hiding our variables so no one messes with it.
So how to hide the variables?
Data hiding using access modifiers
By using access modifiers like: private, public, and protected(you will see it in the inheritance section) we can hide our variables , We also can use them with the methods.
Note1: When we make a variable or a method public, It can be accessed anywhere in the application.
Note2: When we make a variable or a method private, It can be accessed only inside the class who creates it.
So how the user of the class can access the variables after hiding them?
Setters and Getters
By using functions called setters and getters, the user of the class can access the variables, So before assigning value to hidden variables, we make some validations on these data, so we make sure that values the client pass will not mess with our variables.
Here is a code example to clarify the idea :
You can try the code in your IDE
class Person{
private String name;
private int age;
Person(){}
Person(String name ,int age){
setName(name);
setAge(age);
}
private boolean isAlphabetic(String str) {
return str.matches("^[a-zA-Z]+$");
}
private boolean isValidAge(int age) {
return age >= 0 ? true : false;
}
public void setName(String name) {
//some validation on the name
//i will set the name value to the name variable if :
// - the name contains only alphabetic characters
if(isAlphabetic(name)){
this.name = name;
}
else {
System.out.println("Enter a valid name");
}
}
public void setAge(int age) {
//validate the age
//i will set the age value to the age variable if :
// - the age is not a negative number
if(isValidAge(age)) {
this.age = age;
}
else {
System.out.println("Enter a valid age");
}
}
public String getName(){return this.name;}
public int getAge(){return this.age;}
public String toString() {
return "Name of person " + name + " and his/her age is " + age;
}
}The code above is a good example of strong encapsulation. Let’s take each piece of this code and analyze it.
Analyzing the code
We made our variables’ name and age private so no one can access them directly but we provide an access way, These two methods: setName(name) and setAge(age) we made public so the client or the user can assign these values, When calling any of these methods, we first pass the value to a validation function, And notice that I won’t the client to access the validation functions so I make them private.
The client/user can know the values of the variables using getter methods and we make them public so he/her can use them.
Conclusion for the first concept “encapsulation”
- To achieve encapsulation, Combine data and functions in one unit called a class.
- we’ve two types of encapsulation: strong encapsulation and weak encapsulation.
- Hide the variables and functions that you do not want the client/user to access by making them private and giving him/her access to the proper functions that will not affect the encapsulation, so you make a strong encapsulation.
- No data hiding leads to (Weak encapsulation + More complexity)
- Data hiding leads to (Strong/Good encapsulation + Complexity is hidden).
- Why all of this? Prevents external code from accidentally manipulating internal properties/states.
Abstraction
- What is abstraction ?
- Benefits.
- How to achieve ?
What is abstraction ?
Abstraction is about hiding unwanted details while showing most essential in a given context.
Real-life example :
Abstraction in the context of a car refers to the process of separating essential characteristics and behaviors of a car from its implementation details. A car can be abstracted as a vehicle that can transport people or goods from one place to another. The abstraction hides the internal details such as the engine type, transmission system, and other mechanical components that make it possible for the car to move.
Instead, the user interacts with the car through high-level concepts such as starting the engine, accelerating, and braking. This allows for simplicity in the use and understanding of a car, as the user does not need to have a deep understanding of its inner workings to use it effectively.
And also when I change my car from BMW to Mercedes, I do not need to learn how Mercedes works, All cars have the same interface, and they can differ in implementation from one car to another.
Another example of smartphones, When we change from android to apple, We can use each of them using the touch screen, But the type of hardware components and operating system differ.
So abstraction is everywhere in our life.
Benefits
Makes our life easier by giving us the ability to change from one type to another easily and comfortably (Android -> Apple, BMW -> Mercedes).And it reduces the complexity.
How to achieve ?
- Abstraction layer created by encapsulation.
- Abstraction layer created by abstract class and interface (more on that after polymorphism section).
By nature, encapsulation leads to abstraction, because encapsulation hides the object’s details, So how?
Recall the code example in the encapsulation section, I’ll create an object from the class Person.
You can try the code in your IDE
public static void main(String[] args) {
Person p = new Person();
p.setAge(22);
p.setName("Abdelrahman");
}when you use an object of Person class and call its methods, you are indeed using abstraction. By calling the methods, you only need to know what the methods do (i.e., what inputs they take and what outputs they produce), and you do not need to know how the methods do it (implementation).
Another example is when you use the methods inside the String class.
Inheritance
- What is inheritance ?
- Why we use inheritance ?
- Review this design.
- Important condition when dealing with inheritance.
- Composition.
What is inheritance ?
Continue working with the Person class in the encapsulation section(making some changes to demonstrate the idea), Person class represents a general concept of all living humans. This class has properties such as name and age, and methods such as eating ( ) and sleep( ).
//the code is differ from the code in encapsulation section
class Person{
//Note that i change the access modifier for name and age from private to protected
protected String name;
protected int age;
//constructors
Person(){}
Person(String name, int age){
//set name and age
}
public void setters(//values){
//validating values first
//then assing variables with the values
}
public void eat(){
//code to make person eat.
}
public void sleep(){
//code to make person sleep.
}
}Now, Let’s say we want to represent a specific type of person, such as a Student. A student is a type of person who shares many of the same properties and behaviors as other persons. we can create a class Student that inherits from the Person class.
class Student extends Person{
private double gpa;
public void setGpa(double gpa){
//validating the gpa and assign the value.
}
}In this example, the student class has access to all the properties and methods of the Person class, as well as its unique properties and methods.
Note 1: I change the access modifier for name and age, from private to protected so the child class can access and use them.
Note 2: When we make a variable or a method protected, it can be accessed within the same class, within its subclasses, and within classes of the same package.
Why we use inheritance ?
Inheritance allows us to reuse code from the Person class and add new functionality and properties for the Student class.
So the main idea of inheritance is to reuse the code, So no duplication of code or no effort.
Review this design !
What is wrong here ?
public class Engine {
//properties and functions for engine .
}
public class Car extends Engine {
//additional code for car .
}The relationship is wrong, Car is not an Engine. So is there a condition we’ve to consider before using inheritance?
Important condition when dealing with inheritance
Before we use inheritance, we’ve to check if the relationship Is-A.
is the car an engine? of course not.
More on Is-A relationship
- Student is-a person
- Teacher is-a person
- Circle is-a shape, Rectangle is-a shape. Triangle is-a shape
- Software Engineer is-an employee, Manager is an employee, Office Boy is an employee.
- ( Bicycle / Motor vehicle / Railed vehicle) is-a vehicle.
So is there another way for reusing the code if the condition of the Is-A relationship is violated?
Composition
Yup, there is a composition. Look at the code after refactoring it.
public class Engine {
//properties and functions for engine .
}
public class Car {
Engine engine;
Car(Engine engine) {
this.engine = engine;
}
//additional code for car .
}- Composition allows you to create complex objects by combining simple objects.
- It applies to has-a relationship.
More on Has-A relationship
- A car has-an engine and has 4-wheels.
- A building has floors. A floor has apartments.
Benefits of using composition
With composition, you can create complex objects made up of multiple simpler objects, and you can easily swap out components of a composite object without affecting the other parts of the system.
So This allows for greater flexibility.
Polymorphism
Real-life example
This boy behaves in different ways from one situation to another.
So
- In school, he behaves like a student
- At home, he behaves like a son
- On the bus, he behaves like a passenger
- and so on…
Code example
Get Abdulrahman Shaheen’s stories in your inbox
Join Medium for free to get updates from this writer.
Suppose we’ve different types of vehicles, like cars, boats, and airplanes, each of these vehicles overrides the go() function from vehicle class.
Vehicle class: This is the base class that contains a method go().
You can try the code in your IDE
class Vehicle {
public void go(){
System.out.println("Vehicle :)");
}
}Airplane class: This class extends the Vehicle class and overrides the go() method to print "AirPlane is Flying in the sky".
class Airplane extends Vehicle{
@Override
public void go(){
System.out.println("AirPlane is Flying in the sky");
}
}Boat class: This class extends the Vehicle class and overrides the go() method to print "boat is Swimming in the water".
class Boat extends Vehicle{
@Override
public void go(){
System.out.println("boat is Swimming in the water");
}
}Car class: This class extends the Vehicle class and overrides the go() method to print "Car is walking in the street".
class Car extends Vehicle{
@Override
public void go(){
System.out.println("Car is walking in the street");
}
}The main method creates objects of each of the subclasses and stores them in an array of racers of type Vehicle[]. Then, it uses a for-each loop to iterate through the elements in the racers array and calls the go() method for each element, which will print the corresponding message for each type of vehicle.
public class Main {
public static void main(String[] args) {
Car car = new Car();
Boat boat = new Boat();
Airplane airplane = new Airplane();
Vehicle vehicle1 = new Vehicle();
Vehicle[] racers = {car,airplane,boat ,vehicle1};
for(Vehicle vehicle : racers) {
vehicle.go();
}
}
}How is the concept of polymorphism applied in this example?
This code demonstrates polymorphism by using a reference of type Vehicle to refer to objects of different subclasses: Car, Boat, Airplane, and Vehicle. In the for-each loop, the go() method is called on each element of the racers array, which is of type Vehicle[]. This demonstrates polymorphism because each object will call its own implementation of the go() method, even though they are all referred to by a reference of the same type Vehicle. This allows for code to be written more generically and flexibly.
Achieving abstraction using abstract class and interface
- What is abstract class ?
- When to use it ?
- Code example
- why is there abstraction in this code when using abstract class?
- What is interface ?
- When to use it ?
- Code example
- why is there abstraction in this code when using interface?
What is abstract class ?
Here are the properties of the abstract class :
- Cannot be instantiated: An abstract class cannot be instantiated on its own, as it is meant to be used as a base class for other classes.
- Can have abstract methods: An abstract class can have abstract methods(at least one), which are methods that do not have an implementation and must be implemented by the subclasses.
- Can have concrete methods: An abstract class can also have concrete methods, which are methods that have an implementation and can be called directly by objects of the abstract class or its subclasses.
- Can be extended: An abstract class can be extended by another class, which is known as a concrete subclass. The concrete subclass must implement the abstract methods defined in the abstract class.
When to use it ?
When we have some classes that have similar functions and properties but at least one function that behaves differently in each class(and this function will be the abstract function), So we create an abstract class as a base class.
So in general an abstract class provides a common structure for related classes but allows for individual customization through the implementation of abstract methods. This allows you to encapsulate common behavior and state in a single place, while still allowing for flexibility and customization in the individual subclasses.
Code example
You can try the code in your IDE
abstract class Animal {
protected String name;
public Animal(String name) {
//Do not forget to validate the name first and use sitters ,recall encapsulation section :)
this.name = name;
}
public void eat() {
System.out.println(name + " Eating food!");
}
abstract protected void makeSound();
}
class Dog extends Animal {
public Dog(String name) {
super(name);
}
@Override
protected void makeSound() {
System.out.println(name + " barks");
}
protected void dogBehaviour() {
System.out.println("anything dog does!");
}
}
class Cat extends Animal {
protected Cat(String name) {
super(name);
}
@Override
protected void makeSound() {
System.out.println(name + " meows");
}
protected void catBehaviour() {
System.out.println("anything cat does!");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog("Rufus");
Animal cat = new Cat("Mittens");
dog.makeSound();
dog.eat();
cat.makeSound();
cat.eat();
}
}In this example, the Animal class is an abstract class that cannot be instantiated on its own. It has an abstract method makeSound() that must be implemented by its concrete subclasses Dog and Cat. The Dog and Cat classes extend the Animal class and provide an implementation for the makeSound() method.
why is there abstraction in this code when using the abstract class?
The abstraction is achieved here because the client(Main class) can deal only with functions in the animal class and cannot deal with functions in the concreate classes.
In other words: this code uses abstraction to hide the implementation details of the concrete classes (Dog and Cat) and only allows interaction through the abstract class Animal. The client code in Main only knows about the Animal class and its methods (eat and makeSound). The specific behavior of Dog and Cat are hidden and not accessible to the client code. This makes the code more flexible and modular, as changes to the concrete classes won't affect the client code as long as the abstract class interface remains the same.
Depending on what I said overhead, we’ve to ask ourselves some questions to understand what’s going on!
- What are the implementation details of the concrete classes that are hidden in the client?
The implementation details of the concrete classes refer to the specific behavior and characteristics that make each class unique. In the example code, the concrete classes
DogandCathave their unique implementations of themakeSoundmethod, as well as their additional methods (dogBehaviourandcatBehaviour).
2. But we can refer to makeSound method in the client! and you said that the implementation details are hidden, So this violates the abstraction here.
Let’s take this line: Animal dog = new Dog(“Rufus”);
In this line, a
Dogobject is being created and assigned to a reference of typeAnimal. When we call the methodmakeSoundin compiletime it refers to the method in theAnimalclass but in runtime it refers to the actual method ,In this case it refers tomakeSoundin the dog object.So this is polymorphism in action. In the client code, the reference to the
Animalobject is resolved at compile-time and the compiler determines that it can call themakeSoundmethod on it. At runtime, the JVM determines the actual type of the object, whether it's aDogor aCat, and then calls the appropriate implementation of themakeSoundmethod. The reference to theAnimaltype allows for abstraction, as the client does not need to know about the specific implementation of themakeSoundmethod, it only needs to know that it can call themakeSoundmethod on any object of typeAnimal.
NOTE: Interface achieves abstraction as the abstract class achieves it.
What is interface ?
Here are the properties of the interface :
- Cannot be instantiated: Interfaces cannot be instantiated on their own, they must be implemented by a class.
- Only method declarations: Interfaces only contain method signatures, without any implementation. The implementing class must provide the implementation for these methods.
- Multiple inheritance: Interfaces provide a way for a class to inherit the properties and methods from multiple sources since a class can implement multiple interfaces.
- No instance variables: Interfaces cannot have instance variables, only constant variables are allowed.
- Public methods and variables: By convention, all methods and variables in an interface are public.
When to use it ?
You use interfaces when you want to define a blueprint or contract for classes to follow, without providing any implementation. Interfaces are used to provide a common set of methods that multiple classes can implement.
Code example
You can try the code in your IDE
interface Shape {
double getArea();
double getPerimeter();
}
class Rectangle implements Shape {
private double width;
private double height;
//Do not forget to validate the (width and height) first and use sitters ,recall encapsulation section :)
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
@Override
public double getPerimeter() {
return 2 * (width + height);
}
}
class Circle implements Shape {
private double radius;
//Do not forget to validate the radius first and use sitters ,recall encapsulation section :)
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
public class Main {
public static void main(String[] args) {
Shape rectangle = new Rectangle(5, 10);
Shape circle = new Circle(5);
System.out.println("Rectangle area: " + rectangle.getArea());
System.out.println("Rectangle perimeter: " + rectangle.getPerimeter());
System.out.println("Circle area: " + circle.getArea());
System.out.println("Circle perimeter: " + circle.getPerimeter());
}
}In this example, the Shape interface defines two methods, getArea, and getPerimeter, that any class that implements the Shape interface must have. The Rectangle and Circle classes both implement the Shape interface, providing their implementation for the methods defined in the interface.
And any shape we want to create must first implement methods in the shape interface.
why is there abstraction in this code when using interface?
It’s exactly achieved as the abstract class achieved it.
Read the section of abstract class when I demonstrate why the abstraction is achieved.
Connecting Dots by building the pizza app that combine all OOP concepts
- What are we going to build?
- Implementing it without OOP.
- What is the problem with this code ?
- Refactor to the code.
- What are the problem with this code ?
- Implementing the code with OOP.
- Discuss how we achieve each concept of OOP in this app.
What are we going to build?
suppose that there is a person who owns a pizza shop, and this shop sells three types of pizza, which are chicken pizza, beef pizza and cheese pizza. Any kind of pizza goes through three stages before it is served to the customer:
1. The dough making stage
2. The add toppings stage
3. The baking stage.
The only thing that differs from one type of pizza to another is the toppings, knowing that all types use the same dough and will be baked the same way.
Implementing it without OOP
You can try the code in your IDE
public class Main {
public void makeChickenPizza() {
System.out.println("Making dough!");
System.out.println("Adding Chicken to Pizza!");
System.out.println("Backing the Pizza!");
}
public void makeBeefPizza() {
System.out.println("making dough!");
System.out.println("Adding Beef to Pizza!");
System.out.println("Backing the Pizza!");
}
public void makeCheesePizza() {
System.out.println("making dough!");
System.out.println("Adding Cheese to Pizza!");
System.out.println("Backing the Pizza!");
}
public static void main(String[] args) {
System.out.println("Please enter 1)Chicken ,2)beef ,3)Cheese");
int type;
Scanner scanner = new Scanner(System.in);
type = scanner.nextInt();
Main m = new Main();
switch(type){
case 1:
m.makeChickenPizza();
break;
case 2 :
m.makeBeefPizza();
break;
case 3:
m.makeCheesePizza();
break;
default : System.out.println("Invalid choice!");
}
}
}What is the problem with this code ?
Code Duplication: The makeChickenPizza, makeBeefPizza, and makeCheesePizza methods have very similar code, each method of these has the same line one and line three. This violates the DRY (Don’t Repeat Yourself) principle and makes the code harder to maintain.
Refactor to the code
You can try the code in your IDE
public class Main {
private void prepareDough() {
System.out.println("Making dough!");
}
private void addToppings(String toppings) {
System.out.println("Adding "+ toppings +" to Pizza!");
}
private void bakePizza() {
System.out.println("Backing the Pizza!");
}
public void makeChickenPizza() {
prepareDough();
addToppings("Chicken");
bakePizza();
}
public void makeBeefPizza() {
prepareDough();
addToppings("Beef");
bakePizza();
}
public void makeCheesePizza() {
prepareDough();
addToppings("Cheese");
bakePizza();
}
public static void main(String[] args) {
System.out.println("Please enter 1)Chicken ,2)beef ,3)Cheese");
int type;
Scanner scanner = new Scanner(System.in);
type = scanner.nextInt();
Main m = new Main();
switch(type){
case 1:
m.makeChickenPizza();
break;
case 2 :
m.makeBeefPizza();
break;
case 3:
m.makeCheesePizza();
break;
default : System.out.println("Invalid choice!");
}
}
}The problem of duplication code is solved , but there are another problems.
What are the problems with this code ?
There are two problems with this code :
- Lack of Reusability: The code is not reusable. If a new type of pizza is to be added, the entire process of making the pizza has to be repeated with a new method.
- Lack of Abstraction: There is no abstraction in the code. And this leads to high dependency. Each part of the code is dependent on the other part. If you were to add a new step in the process of making a pizza, you will modify all the functions in the pizza app. It leads also to a decrease in code readability, maintainability, and modularity. And it makes the code harder to modify, extend, or debug, and also makes it more difficult to reuse the code for other similar projects.
OOP comes with some tools to solve these serious problems.
Implementing the code using OOP
First, think about the similarities and differences between all types of pizza. The types have the same process of making dough and baking the pizza, the only difference is the toppings added to the pizza.
We know that add topping process is different from type to another ,So I made an abstract function called specializedToppings() and each type of the pizza implemented it.
You can try the code in your IDE
abstract class Pizza {
private void bakePizza(){
System.out.println("Baking pizza!");
}
private void prepareDough(){
System.out.println("Making Dough!");
}
private void addToppings(){
System.out.println("Adding topping to " + specializedToppings() + " pizza!");
}
protected abstract String specializedToppings();
public void makeOrder(){
prepareDough();
addToppings();
bakePizza();
}
}
class BeefPizza extends Pizza{
protected String specializedToppings(){
return "Beef";
}
}
class CheesePizza extends Pizza{
@Override
public String specializedToppings(){
return "Cheese";
}
}
class ChickenPizza extends Pizza{
protected String specializedToppings(){
return "Chicken";
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Please enter 1)Chicken ,2)beef ,3)Cheese");
int type;
Scanner scanner = new Scanner(System.in);
type = scanner.nextInt();
Pizza pizza;
switch(type){
case 1:
pizza = new ChickenPizza();
pizza.makeOrder();
break;
case 2 :
pizza = new BeefPizza();
pizza.makeOrder();
break;
case 3:
pizza = new CheesePizza();
pizza.makeOrder();
break;
default : System.out.println("Invalid choice!");
}
}
}Discussing how we achieved each concept of OOP in this app
- Encapsulation: the methods
prepareDough,addToppings, andbakePizzaare defined asprivate, which means they are only accessible within thePizzaclass. This encapsulates the implementation details of making a pizza within the class and prevents other codes from accessing or modifying these methods directly. The methodmakeOrder()is defined aspublic(it works as a public API) and encapsulates the process of making a pizza by calling the methodsprepareDough(),addToppings(), andbakePizza()in order. This means that the code in theMainclass does not need to worry about the specific details of how the pizza is made, as those details are encapsulated within themakeOrder()method. The methodspecializedToppings()is defined asprotectedand it is an abstract method, which means that it must be implemented by the subclasses of thePizzaclass. This method allows each subclass to specify its own toppings. Determining the right access modifier here makes the encapsulation strong. - Abstraction: After achieving encapsulation we achieve the first layer of abstraction, Also abstraction is achieved by creating an abstract class
Pizzaand declaring some of its methods as abstract. The abstract methodspecializeToppingsmust be implemented by any concrete class that extends thePizzaclass. This allows the abstract class to define a general structure and behavior that must be followed by all concrete classes, while also allowing each concrete class to specialize and define its own unique behavior. The implementation details of making a specific type of pizza (such as beef, chicken, or cheese) are hidden behind the abstraction so that changes to the implementation of one type of pizza do not affect the implementation of other types. - Inheritance: Inheritance is achieved in this code by defining an abstract class
Pizzawhich acts as a blueprint for other concrete classes (e.g. ChickenPizza, BeefPizza, and CheesePizza) to inherit from. The concrete classes extend the abstract class and provide their own implementation for the abstract methodspecializeToppings. This allows for code reuse as the implementation for common methods (e.g.prepareDoughandbakePizzacan be defined in the abstract class, and then shared by the concrete classes without having to be repeated in each one. - Polymorphism: Polymorphism is achieved in this code by the use of method overriding. The
specializeToppingsmethod is declared in the abstractPizzaclass, but it is overridden by the concrete classesBeefPizza,CheesePizza, andChickenPizzato provide their own implementation. As a result, whenmakeOrderis called on instances of these concrete classes, the behavior of theaddToppingsmethod is specialized to the type of pizza being made. For example, if we callmakeOrderon aChickenPizzaobject, it will call theprepareDoughandbakePizzamethods as specified in the abstractPizzaclass, but it will also use the specializedspecializeToppingsimplementation in theChickenPizzaclass, to add the appropriate toppings to the pizza.
So why the final version of this app is good?
Because if we try to extend the app by adding new types of pizza (such as SeafoodPizza) we will simply create a new class that extends the abstract class Pizza and provide an implementation of the specializeToppings method.
Additionally, the abstraction achieved through the use of an abstract class and inheritance makes it easy to extend or modify the code in the future. For example, if you wanted to add a new step to the process of making pizza, you could add a new method in the abstract class, and it would automatically be available in all the derived classes.
Try to change or add something to the pizza app in the version in which we did not apply the OOP principles, It will be messy :(
Resources
- https://www.udemy.com/course/cpp-4skills/
- Mohamed Moshrif [Interview course]






