Tutorial

OOPS Concepts in Java - OOPS Concepts Example

Published on August 3, 2022
author

Pankaj

OOPS Concepts in Java - OOPS Concepts Example

Object-Oriented Programming Concepts are very important for programming. Without having an idea about OOPS concepts, you will not be able to design systems in the object-oriented programming model.

What is Object-Oriented Programming Model?

The object-oriented programming model revolves around the concept of Objects. What is an Object? An object is an instance of a Class. It contains properties and functions. They are like real-world objects. For example, your car, house, laptop, etc. are all objects. They have some specific properties and methods to perform some action. What is a Class? The Class defines the blueprint of Objects. They define the properties and functionalities of the objects. For example, Laptop is a class and your laptop is an instance of it.

OOPS Concepts

oops concepts, object oriented programming concepts, oops concepts in java Core OOPS concepts are:

  1. Abstraction
  2. Encapsulation
  3. Polymorphism
  4. Inheritance
  5. Association
  6. Aggregation
  7. Composition

Let’s look into these object-oriented programming concepts one by one. We will use Java programming language for code examples so that you know how to implement OOPS concepts in Java.

1. Abstraction

Abstraction is the concept of hiding the internal details and describing things in simple terms. For example, a method that adds two integers. The internal processing of the method is hidden from the outer world. There are many ways to achieve abstraction in object-oriented programmings, such as encapsulation and inheritance. A Java program is also a great example of abstraction. Here java takes care of converting simple statements to machine language and hides the inner implementation details from the outer world.

Further Reading: What is Abstraction in OOPS?

2. Encapsulation

Encapsulation is the technique used to implement abstraction in object-oriented programming. Encapsulation is used for access restriction to class members and methods. Access modifier keywords are used for encapsulation in object oriented programming. For example, encapsulation in java is achieved using private, protected and public keywords.

3. Polymorphism

Polymorphism is the concept where an object behaves differently in different situations. There are two types of polymorphism - compile time polymorphism and runtime polymorphism. Compile-time polymorphism is achieved by method overloading. For example, we can have a class as below.

public class Circle {

	public void draw(){
		System.out.println("Drwaing circle with default color Black and diameter 1 cm.");
	}
	
	public void draw(int diameter){
		System.out.println("Drwaing circle with default color Black and diameter"+diameter+" cm.");
	}
	
	public void draw(int diameter, String color){
		System.out.println("Drwaing circle with color"+color+" and diameter"+diameter+" cm.");
	}
}

Here we have multiple draw methods but they have different behavior. This is a case of method overloading because all the methods name is same and arguments are different. Here compiler will be able to identify the method to invoke at compile-time, hence it’s called compile-time polymorphism. Runtime polymorphism is implemented when we have an “IS-A” relationship between objects. This is also called a method overriding because the subclass has to override the superclass method for runtime polymorphism. If we are working in terms of the superclass, the actual implementation class is decided at runtime. The compiler is not able to decide which class method will be invoked. This decision is done at runtime, hence the name as runtime polymorphism or dynamic method dispatch.

package com.journaldev.test;

public interface Shape {

	public void draw();
}
package com.journaldev.test;

public class Circle implements Shape{

	@Override
	public void draw(){
		System.out.println("Drwaing circle");
	}

}
package com.journaldev.test;

public class Square implements Shape {

	@Override
	public void draw() {
		System.out.println("Drawing Square");
	}

}

Shape is the superclass and there are two subclasses Circle and Square. Below is an example of runtime polymorphism.

Shape sh = new Circle();
sh.draw();

Shape sh1 = getShape(); //some third party logic to determine shape
sh1.draw();

In the above examples, java compiler doesn’t know the actual implementation class of Shape that will be used at runtime, hence runtime polymorphism.

4. Inheritance

Inheritance is the object-oriented programming concept where an object is based on another object. Inheritance is the mechanism of code reuse. The object that is getting inherited is called the superclass and the object that inherits the superclass is called a subclass. We use extends keyword in java to implement inheritance. Below is a simple example of inheritance in java.

package com.journaldev.java.examples1;

class SuperClassA {

	public void foo(){
		System.out.println("SuperClassA");
	}
	
}

class SubClassB extends SuperClassA{
		
	public void bar(){
		System.out.println("SubClassB");
	}
	
}

public class Test {
	public static void main(String args[]){
		SubClassB a = new SubClassB();
		
		a.foo();
		a.bar();
	}
}

5. Association

Association is the OOPS concept to define the relationship between objects. The association defines the multiplicity between objects. For example Teacher and Student objects. There is a one-to-many relationship between a teacher and students. Similarly, a student can have a one-to-many relationship with teacher objects. However, both student and teacher objects are independent of each other.

Aggregation

Aggregation is a special type of association. In aggregation, objects have their own life cycle but there is ownership. Whenever we have “HAS-A” relationship between objects and ownership then it’s a case of aggregation.

6. Composition

The composition is a special case of aggregation. The composition is a more restrictive form of aggregation. When the contained object in “HAS-A” relationship can’t exist on its own, then it’s a case of composition. For example, House has-a Room. Here the room can’t exist without the house. Composition is said to be better than inheritance, read more at Composition vs Inheritance.

Further Reading: Composition in Java

That’s all for a quick round-up on OOPS concepts.

You can go through more Java example programs from our GitHub Repository.

References: https://docs.oracle.com/javase/tutorial/java/concepts/

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
December 20, 2020

Thanks guy, I did appreciate your explanations. You helped me have clear ideas of the different concepts.

- emmanuel

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    August 12, 2020

    OSM Interface … nd also All Concept Easy to Understand

    - VISHVANATH METKARI

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      July 3, 2020

      How to write this programm in java Class Teacher Name Department gender salary grade with paramatarised constructor

      - Pirzada

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        January 7, 2020

        “Shape sh = new Circle(); sh.draw();” how to understand that it only can be done at runtime? i think as long as the complier is strong enough, the complier could also know which to call at complie time. thank you

        - Roy Wu

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          September 6, 2019

          Super… Thanks Pankaj

          - Ashok Burania

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            August 26, 2019

            Hi Pankaj, thank you very much for so much information about Java and all in the same place. It was great idea doing that. I have read lots of your articles. Allow me to point something that doesn’t sound right, when you say: “Shape is the superclass and there are two subclasses Circle and Square.” shouldn’t it be: “Shape is an interface and Circle and Square are implementations of it, which give us an Interface polymorphism.” ?

            - Bruno

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              August 13, 2019

              nice very very nice i love it… ha ha ha ha

              - Boss shivaji the boss

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                August 7, 2019

                Thank you for sharing such an informative and useful post with us.

                - preeti

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  June 5, 2019

                  excellent,super

                  - Senuja Ranhira

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    May 14, 2019

                    Very simple and nice

                    - Sudeep

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Become a contributor for community

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.