Geya Sahithi
Geya Sahithi's Blog

Follow

Geya Sahithi's Blog

Follow
Don't say oops(πŸ™€)! Learn OOPs with Java

Don't say oops(πŸ™€)! Learn OOPs with Java

Geya Sahithi's photo
Geya Sahithi
Β·Oct 5, 2022Β·

7 min read

Oops!… I did it again. I played with your heart, got lost in the game. No that's not the Oops we're going to talk about. We're going to talk about OOP(Object Oriented Programming). We are going to dive into the deep ocean of functionalities and characteristics of OOPs. What was before OOPs, why OOPs, and how does it make our life easier?

History time!

Let's start traditionally by asking what was before OOPs. Before OOPs, Procedural programming was used. It divides a program into a set of functions, in which data was stored under a variable and functions used to operate on this data. The disadvantage of Procedural oriented programming is that the lengthy code is difficult and tiresome to edit. The functions in the code are so interdependent that it becomes knotty. It is even called a "spaghetti code" because the code becomes complicated.

giphy (1).gif

Object Oriented Programming came to solve this problem. It combined properties(variables) and methods(functions) into a single unit called an Object. For example, if we take a Car as an object then its properties will be its color, size, model, etc., and its methods will be of start(), stop(), break(), etc. Languages that operate in OOP are Java, C++, and Python. Objects and Classes are two important keywords in OOP. We have already seen what objects are. Classes are the blueprint of an object. For example, we can say a Car is the blueprint of the object Mustang or the vehicle class contains the object car.

image.png

The four pillars of OOP

  1. Encapsulation
  2. Inheritance
  3. Abstraction
  4. Polymorphism

Encapsulation

As the name suggests it refers to the bundling of data into one. We have already discussed the variables and functions getting combined into one unit as an object.

Note: At least some of you might doubt if the variables and functions are wrapped up into a class or an object. Objects and classes can be used interchangeably here because an object is the instance of a class.

Add a little bit of body text.png

Encapsulation also restricts direct access to data which is called data hiding. This prevents outsiders access the code. Encapsulation can be achieved by the access modifier, private. As we know the private variable data can only be accessed from within the class it is defined in. Using the get and set function we can modify that data to access and update the data of a private variable. Example:

public class Encapsulation {
    public static void main(String[] args) {

        BankAccount obj = new BankAccount();
        obj.setAmount(1234, 100);
        System.out.println(obj.getAmount());
    }
}

class BankAccount {

     int otp = 1234;
     private int amount;
    public void setAmount(int otp, int amount){
        if(otp == this.otp){
            this.amount = amount;
        }
    }
    public int getAmount(){
        return amount;
    }
}

Output

100

Here, by using the set function, two parameters, amount and OTP is set for the object BankAccount in the Main class. If the variable OTP in the class BankAccount is the same as the parameter of the main class, the amount variable is set to 100. Now, the object obj calls the method getAmount() which returns the value of the variable amount.

Note: Class attributes can be made read-only by using only getters and write-only by using only setters.

Interface - Interfaces implement superclass like child class extends superclass. Why do we need an interface if there is already a function by which a child class can extend its superclass? Java does not support multiple inheritance. This is where "interface" comes in. Interface is used to achieve abstraction and multiple inheritance in Java.

interface Person {
    void walk();
}
interface LivingBeing {
    void walk();
    void breath();
} 
class Employee implements Person, LivingBeing {
    @Override
    public void walk() {    
    }
    @Override
    public void breath() {
    }    
}

Some more facts on Abstraction

  • You can store an abstract function and a non-abstract function in an abstract class but, not the opposite.
  • All the methods defined in interface are by default abstract and public.
  • Objects cannot be created in an abstract class because it is just an idea and not real-world entity.

Inheritance

Inheritance is the mechanism by which Java allows one class to access the data and functions of another class.

giphy (3).gif

Super Class / Parent Class: Super Class is the class from which the data can be inherited.

Sub Class / Child Class: Sub Class is the class that inherits/can access all the data and functions. It can also have its own methods and functions besides the superclass.

In the below example, the class Samsung is the child class. It uses the keyword "extends" to access the parent class which is MobilePhone.

class MobilePhone {
    boolean hasHeadphoneJack;
    String os;
    int price;
    void playGames(){
        System.out.println("Mobile phone playing games");
    }
    void playGames(int x){
        for(int i = 0; i<x; i++){
            System.out.println("Playing games");
        }      
    }
}
class Samsung extends MobilePhone{
    void playGames(){
        System.out.println("Samsung playing games");
    }
}

Output

Samsung playing games
Mobile phone playing games

Different types of inheritance in Java

  1. Single Inheritance - In this only one child class extends or inherits from the subclass.
  2. Multilevel inheritance - Here, a base class becomes the superclass of an intermediate class and this intermediate class becomes a superclass for a subclass. In Java, a class cannot directly access the members of the grandparent class.
  3. Hierarchical Inheritance - One class serves as a superclass and all the other classes become its child class.
  4. Multiple inheritance -This is the property by which a child class has two parent classes. This is not supported by Java.

Abstraction

Data abstraction is the property by which only the details which are essential to the user are set forth. The trivial or non-essential details are hidden from the user for convenience. Abstraction is the layer that separates us from the hardware of our computer and the UI we see. It is the layer on which multiple programs are made. For example, when we turn on the fan's switch we don't think about all the things that happen behind it, we just see the fan running. Most often the function abstraction and encapsulation are mixed up. Encapsulation is used for security reasons and abstraction is used for hiding the complex code and only showing what is required of the user.

giphy (4).gif

Abstraction is achieved by two different methods

  • Abstract keyword
  • Interface

Abstract Keyword - The abstract keyword creates a method of an idea. It is a non-access modifier.

Override - Overriding is a feature that allows a subclass or a child class to provide a specific implementation of a function that is already defined in its superclass or parent class. The method/function of the subclass overrides the method in the superclass. When there is an error in the name of the overridden function overriding gives a compile time error rather than a logical error.

abstract class Vehicle {
    abstract void starts();
    void breaks() { 
        System.out.println("vehicle breaks");
    }
}
class Scooty extends Vehicle {
    @Override
    void starts() {
    }
}
class Car extends Vehicle {
    @Override
    void starts() {
    }
}

Polymorphism

We're going to start by dissecting the word polymorphism into two. Poly means many and morph means forms. So, polymorphism means "many forms". For example, the same person can be an office employee, a singer, a guitarist, a dancer, and whatnot. The same person, different qualities. This feature in Java is achieved in two different ways. Compile time polymorphism and runtime polymorphism.

image.png

Compile time Polymorphism - Also known as static polymorphism. Runtime polymorphism is achieved by Method Overloading.

Method overloading - With the help of this property multiple methods or functions can be written with different sets of parameters.

public class LearningOverloading {
    public static void main(String[] args) {
        System.out.println(sum(2, 3));
        System.out.println(sum(4, 6, 8));

        System.out.println(sum("Hiyee"));
    }
    public static int sum(int x, int y) {
        return x + y;
    }
    public static int sum(int x, int y, int z) {
        return x + y + z;
    }
    public static String sum(String sayHi) {
        return sayHi;
    }
}

Runtime Polymorphism - Also known as Dynamic polymorphism. Runtime polymorphism is achieved by method overriding, about which we have already discussed.

Difference between "Method overloading" and "Method overriding" Overloading has the same function different signature. Overriding has the same function, same signature but different class, connected through inheritance.

That is all about OOP and its four pillars. Hope you liked the articleπŸ€—. Thank you for reading. We can connect through Twitter. Have a nice day folks!!

Β 
Share this