Home

 › 

Articles

 › 

Object Oriented Programming (OOPs) Concept in Java – With Examples

OOPs in Java

Object Oriented Programming (OOPs) Concept in Java – With Examples

Object Oriented Programming is the coding paradigm behind the development of most great projects in our programming world. OOPs in Java are also one of the main topics every developer must learn at least a little bit about in their career, even if they won’t specialize in this language.

Today we’ll focus on the Java environment, but OOPs concepts are similar in every modern language. So, once you understand the basics, you will be able to use this logic in any project you want and (with some degree of variance) in any language you want.

Our goal is to teach you the fundamentals: classes, objects, and more. Every piece of information will lead you further on your programming journey.

What is Object Oriented Programming?

Object Oriented Programming is built around the use of objects. In OOPs (here, the “s” stands for “systems”), every object contains information or some other code values, usually called state and behavior.

In general, programming objects model the real-world objects we find every day in our life. As such, objects have properties and states that describe their relevant characteristics. 

We’ll keep talking about objects later, but first, let’s learn about classes.

Classes in OOPs

In OOPs, we define a class as the blueprint necessary for creating objects. If an object models real-world objects, then a class defines the basics of their state and behavior that will be the bricks and mortar of our code’s logic. 

Once we have a class, we can create as many objects as necessary. Don’t worry if this seems too abstract now, as we’ll be showing you code examples in no time. 

A class is created using the class keyword, and should always have a capitalized first letter. Let’s see how:

class Name
{
    // attributes
    // methods
}
OOPs in Java
How to create a class in Java.

©History-Computer.com

Here, we have the class keyword that creates the class called Name. Then, we define the attributes and methods inside the curly braces, also known as the body.

The method is simple and easy to understand, so now let’s try to create a real-life object:

public class Car
{
    int n = 10;

    public static void main(String[] args)
    {
        Number myN = new Number();
        System.out.println(myN.n);
     }
}
A simple program to define an object.

©History-Computer.com

In the above example, we define our class using states and behaviors. These statements allow us to distinguish one object from another. 

Now, every time we create a new “car” object, it will be made using the same blueprint, but every attribute’s values will change. 

We call every particular object created from one class an instance of that class, and we can have as many instances as we require. In this example, once we have defined that all cars have an attribute “color,” then we can create a blue car, a red car, a white car, etc. 

Methods in Java OOPs

Now come what we call methods. In OOPs, methods are actions that belong to the object and can be reutilized every time we want. Think of them as functions that can only run when applied to a specific object. For example, there might be a method for reorganizing strings that only works with the “string” object. 

Therefore, methods contribute to creating a cleaner syntax. Additionally, Java includes some built-in methods that we can use to expand our code’s functionality in combination with user-defined methods.

The code may look complicated, but the key principle is that every attribute is just a characteristic like color or speed. In contrast, a method is what action this object can accomplish.

Objects, classes, and methods are the bread and butter of OOPs, so take your time to work through these last few paragraphs before moving on. 

What is Encapsulation?

In Object-Oriented Programming, we have four pillars that hold everything together. These pillars are called Encapsulation, Inheritance, Abstraction, and Polymorphism. Let’s just get into them. 

Encapsulation is a security practice that protects the data in our code. In other words, encapsulation prevents access of regular users to sensitive information.

Let’s see how to write encapsulated values:

public class Person
{
    private String name;  // private statement

    //Get
    publish String getName()
    {
        return name;
    }

    // Set
    public void setName(String newName)
    {
        this.name = newName;
    }
}
A program to illustrate the getter and setter methods.

©History-Computer.com

In the above example, we declared some variables or class attributes as private, and then we added the Get and Set methods. Get and Set allows us to change private attributes using the right keywords.

How Inheritance Works

Inheritance is a class-defining tool that allows us to create classes with attributes and methods inherited from another class. 

For example, a gas car, an electric car, and a truck have many common characteristics, like speed, acceleration, and efficiency. But, some other attributes like battery charge may be unique to only one class.

Luckily for us, Inheritance will help us define a slightly different class without having to write all the common attributes again. Also, methods can be either inherited or uniquely defined for each sub-class.

In OOPs, we call the superclass from which another is derived the “parent” class and the derived subclass the “child” class. Let’s see an example:

class Person
{
    String name;
    
    public void sayHi()
    {
        System.out.println("Hi!");
    }
}

//subclass
class Mary extends Person
{
    public void display()
    {
        System.out.println("My name is " + name);
    }
}

class Main
{
    public static void main(String[] args)
    {
        Mary comedian = new Mary();
        people.name = "Mary";
        people.display();
        
        Mary.sayHi();
     }
}
Inheritance is illustrated with this example.

©History-Computer.com

In the above code, we first write the superclass name. Then, we establish the “extends” keyword, followed by the subclass name. 

Here, we may not see them, but all of the fields and methods from the superclass are included in the body. On top of it, we can add as many new attributes as we need.

This approach avoids repetition and leads us to an easy-to-understand code.

Polymorphism Explained

As we saw before, inheritance is the ideal way to create a series of classes related to each other. It’s one of the defining characteristics of Object Oriented Programming that make it preferable to other paradigms.

Now, there’s more! We can add an interesting twist to the already great capabilities of Inheritance with Polymorphism.

In OOPs, Polymorphism refers to an object’s capacity to have different characteristics depending on how it’s classified. For example, a dog can be a pet and a mammal simultaneously.

Let’s apply this concept so its easier to understand: 

class Person
{
    public void sayHi()
    {
        System.out.println("Say hi!");
    }
}
class George extends Person
{
    public void sayHi()
    {
        System.out.println("George says hi!");
    }
}
class Jerry extends Person
{
    public void sayHi()
    {
        System.out.println("Jerry says hi!");
    }
}

class Main
{
    public static void main(String[]args)
    {
     Person newPerson = new Person();
     Person newGeorge = new George();
     Person newJerry = new Jerry();

     newPerson.sayHi();
     newGeorge.sayHi();
     newJerry.sayHi();
     }
}
The concept of polymorphism is illustrated in a program.

©History-Computer.com

Here, we create two new objects from the same parent class. They have the same method, but the return changes depending on what we assign as value. 

Polymorphism and inheritance are two notable features of Object Oriented Programming, so take all the time you need to understand them!

Abstraction in Java OOPs

In Object Oriented Programming, we may have situations where we want to show only essential statements of an object. 

It may be the case that because of security matters, users should not be allowed to access certain information. Or maybe we simply want to simplify how our code looks and works.

In any case, Abstraction is the usual method to show or hide information intentionally. For example, some aspects of a website are hidden from the regular user and only available to the web developer. 

To achieve abstraction, we need to use the keyword of the same name, and we can decide to abstract classes or methods.

If we choose to abstract a class, this cannot be used to create objects. The only way to do this action is by an inherited class. 

On the other hand, an abstract method doesn’t have a body of information, it’s only defined by inheriting from a parent class.  

Let’s see an example: 

//Abstract class
abstract class Human
{
    //Abstract method (does not have a body)
    public abstract void personHi();
    //Regular method
    public void sleep()
    {
         System.out.println("Zzzz");
    }
}

//Subclass (inherit from Animal)
class Person extends Human
{
     public void personHi()
     {
      // the body of personHi() is provided here
         System.out.println("Hello!");
     }
}
class Main
{
    public static void main (String[] args)
    {
          Person newPerson = new Person();
          newPerson.personHi();
          newPerson.sleep();
     }
}
A program to illustrate abstract classes in Java.

©History-Computer.com

Conclusion: Object Oriented Programming (OOPs) in Java – With Examples

We have reached the end of the article, and so far, we’ve covered all the fundamentals of OOPs that any beginner should know about! Let’s do a quick recap. 

Classes, objects, and methods will get you a long way in your programming journey. They will be important when developing your ideas and will help you understand the logic behind any program.

Also, now you know the four pillars of OOPs: Encapsulation, Inheritance, Polymorphism, and Abstraction. They all underlie the code of any application and are the core features of OOPs. 

These are all the necessary tools to get you started in OOPs. But, if you want to learn more you should take a look at Java’s official documentation.

Frequently Asked Questions

What is Object Oriented Programming?

In computer science, Object Oriented Programming is a software-building paradigm. In OOP systems, objects contain methods and attributes, and they are the standard way of encapsulating information.

How does inheritance work?

Inheritance allows us to create a child class from a parent class. In this process, our new class inherits all the attributes and methods from the parent class.

How can we define an OOPs object?

An object is the centerpiece of any OOPs structure because it contains information such as attributes and behaviors. You define an object by creating an instance of a class or a subclass. 

What are classes in Object Oriented Programming?

In OOPs, a class is a blueprint for creating objects, and it defines the attributes and behaviors of objects. They can inherit their properties via inheritance, such that a class acts as a child class of a larger parent class that defines most of its attributes.

When was Java released?

Java was released in June 1991. It’s a prevalent programming language designed by James Gosling, Mike Sheridan, and Patrick Naughton. It has remained one of the most popular languages thanks to its versatility and logical use of OOP concepts.

To top