Simran Kaur Arora | 21 Aug, 2023

OOP Concepts In Java with Examples

Let's discuss OOPS concepts in Java. Our article introduces each concept, explains the foundation, and provides examples. After all, that's why we rely on object-oriented programming (OOP). They're practical.

While this article focuses specifically on OOP concepts in Java, the ideas are language-agnostic. Object-oriented programming concepts apply across languages, so you should be able to use them in C++, Ada, Pascal, and Java

Definition of OOPS Concepts in Java

Before we get started, let's discuss the basics. What is OOP?

Let's make it super simple. Picture those toy blocks you used when you were a kid. We can relate Object-Oriented Programming to those toy building-block structures:

  1. Class: Think of a class as the blueprint or instruction manual for a specific block structure. It tells you what pieces you need and how they fit together.

  2. Object: This is the actual block structure you build using that blueprint.

  3. Inheritance: It's like getting a hand-me-down toy set from an older sibling. Your new set already has a lot of pieces from the old set, but you can add some new ones or change it up a bit.

  4. Polymorphism: Imagine you have a piece that can change its shape based on where you put it in your structure. In the programming world, depending on the situation, a function can act a little differently.

  5. Abstraction: Instead of seeing every tiny detail and complexity of your model, you just see the overall shape and color. It’s like squinting your eyes and looking at the big picture without all the tiny details.

  6. Encapsulation: It's like building a little box and deciding who can open it, who can look inside, or who can change what’s inside. You have control over it.

  7. Association: Think of it as different block sets having some connection. Like, a block person and a block car. The person doesn’t own the car, but they can drive it.

  8. Aggregation: Here, one block set kind of owns another. Like, you have a toy house, and inside are toy furniture sets. The furniture belongs to the house but can also exist on its own.

  9. Composition: This is like having a toy person and a toy hat. If the person disappears (poof!), the hat goes too, because, well, who's it gonna fit on?

So, Java, like many cool modern languages, uses these concepts. This helps make things neat, and organized, and makes sure parts fit together nicely—just like in a world of toy blocks! Need a deeper understanding? Learn Java.

OOP Paradigm 

The primary objective of the object-oriented approach is to eliminate some of the pitfalls that exist in the procedural approach. OOP treats data as an element in the program, not allowing it to flow around the system freely. It ties data closely to the functions that operate on it and protects it from unintentional modification by other existing functions.

Object-oriented programming allows decomposing a problem into several entities called Objects and then building data and functions from these entities. The combination of the data makes up an object. 

Object = Method + Data 

The data of an object is accessed by the methods associated with that object. However, the methods of an object can access methods of other objects. 

Features of OOPS

Some features of object-oriented programming in java are: 

  • Emphasis is on data (rather than procedures)
  • Programs are divided into objects
  • Data Structures are designed to characterize objects
  • Methods operating on the data of an object are tied together in the data structure 
  • Data is hidden, and external functions cannot access it
  • Objects communicate with each other through methods
  • New methods and data can be easily added whenever necessary
  • Follows the bottom-up approach in program design

Let's break that down with an example.

Imagine you're cooking in a big, busy kitchen:

  1. Emphasis is on data than procedures: It's like focusing more on the ingredients (like tomatoes, onions, and spices) rather than just the recipe. You know the quality of your dish will be based on the freshness and goodness of those ingredients.

  2. Programs are divided into objects: Think of these as different stations in your kitchen: the chopping station, the frying pan, and the oven. Each has its own role in making your meal come together.

  3. Data Structures characterize objects: It’s like having specific containers for each ingredient - a spice rack, a veggie drawer, an oven tray. These containers tell you a lot about what goes inside them.

  4. Methods tied together in the data structure: Imagine you have a recipe card attached to each container. The card doesn’t just list ingredients, but also tells you what to do with them—like chop, sauté, or bake.

  5. Data is hidden; external functions can't access it: This is the chef's secret sauce! You know there’s something magical in it, but the exact recipe? That's locked away in a vault. Others can enjoy the taste but can't mess with the original.

  6. Objects communicate through methods: It’s like the stove signaling to you when the oven is preheated or the blender telling you it’s done mixing. They don't talk (obviously), but they have ways (or methods) to communicate their status.

  7. Easily add new methods and data: Just got a new recipe or a fresh ingredient? No worries! You can easily add them to your cooking process. It’s like upgrading your menu without redoing the entire kitchen.

  8. The bottom-up approach in design: Instead of deciding on the full menu first, you decide on individual dishes. Like, “Hey, I want to make a killer spaghetti!” and then you think of adding garlic bread and a salad to the mix.

So, in a nutshell, Java's OOP is like cooking up a feast in a well-organized kitchen. Everything has its place, and it all works together to create a delicious, cohesive meal!

List of OOPS Concepts in Java with Examples

General OOPS concepts in Java are:

Objects and Classes 

Objects are runtime entities in an object-oriented system. An object can represent a person, a bank account, a place, or a table of data. It may also represent user-defined data types like lists and vectors. Any programming problem is analyzed based on objects and how they communicate amongst themselves. The objects interact with each other by sending messages to one another when a program is executed.

For Example, ‘customer’ and ‘account’ are two objects that may send a message to the account object requesting for the balance. Each object contains code and data to manipulate the data. Objects can even interact without knowing the details of each other’s code or data. 

The entire set of code and data of an object can be made user-defined data type using the concept of the class. A class is a ‘data type’ and an object is a ‘variable’ of that type. Any number of objects can be created after a class is created.

The collection of objects of similar types is termed a class. For Example, apples, oranges, and mangos are the objects of the class Fruit. Classes behave like built-in data types of a programming language but are user-defined data types. 

Representation of an Object 

Data Abstraction and Encapsulation 

The wrapping up of the data and methods into a single unit is known as encapsulation. The data is accessible only to those methods, which are wrapped in the class, and not to the outside world. This insulation of data from the direct access of the program is called data hiding.

Encapsulation of the object makes it possible for the objects to be treated like ‘black boxes’ that perform a specific task without any concern for internal implementation. 

Encapsulation- Objects as “black boxes”

Abstraction is the act of reducing programming complexity by representing essential features without including background explanations or details. Classes are the concept of abstraction and are defined as the list of abstract attributes such as size, weight, cost, and methods that operate on these attributes. Classes wrap or encapsulate all the essential properties of the objects that are to be created. 

Abstract classes and Abstract methods:

  1. An abstract class is a class with an abstract keyword.
  2. An abstract method is a method declared without a method body.
  3. An abstract class may not have all the abstract methods. Some methods are concrete. 
  4. A method-defined abstract must have its implementation in the derived class, thus making method overriding compulsory. Making a subclass abstract avoids overriding. 
  5. Classes that contain abstract method(s) must be declared with abstract keywords.
  6. The object for an abstract class cannot be instantiated with the new operator. 
  7. An abstract class can have parameterized constructors.

Ways to achieve abstraction: 

  • Using abstract keyword
  • Using interfaces

Example Code: 

The code below shows an example of abstraction.

abstract class Car
{
 Car()
 {
  System.out.println("Car is built. ");
 }
 abstract void drive();
 void gearChange()
 {
  System.out.println("Gearchanged!!");
 }
} 

class Tesla extends Car
 {
  void drive()
  {
   System.out.println("Drive Safely");
  }
 }

class Abstraction 
 {
  public static void main (String args[])
  {
   Car obj = new Tesla();
   obj.drive();
   obj. gearChange();
  }
 }

Inheritance 

Inheritance is the process by which objects of one class acquire some properties of objects of another class. Inheritance supports the concept of hierarchical classification. For Example, a bird Robin is part of the class, not a mammal, which is again a part of the class Animal. The principle behind this division is that each subclass shares common characteristics from the class from its parent class. 

 

Properties of Inheritance 

In OOP, the idea of inheritance provides the concept of reusability. It means that we can add additional features to parent class without modification; this is possible by deriving a new class from the parent class. The new class consists of the combined features from both the classes. In Java, the derived class is also known as the subclass. 

Types of Inheritance 

  • Single 
  • Multiple 
  • Multilevel
  • Hybrid 

Example Code: 

The code below illustrates an example of Inheritance. 

class Animal 
{
 void eat()
 {
  System.out.println("I am a omnivorous!! ");
 }
}

class Mammal extends Animal 
{
 void nature()
 {
  System.out.println("I am a mammal!! ");
 }
}

class Dog extends Mammal 
{
 void sound()
 {
  System.out.println("I bark!! ");
 }
}

class Inheritance 
{
 public static void main(String args[])
 {
  Dog d = new Dog();
  d.eat();
  d.nature();
  d.sound();
 }
}

Polymorphism 

Polymorphism is an important OOP concept; it means the ability to take many forms. For Example, an operation exhibits different behavior in different situations. The behavior depends on the type of data used in the operation. For Example, in the operation of addition, the operation generates a sum for two numbers. If the operands are strings, then a third string is produced by the operation by concatenation. 

The figure below demonstrates that a single function name can be used to handle the different numbers and different types of arguments. For more on this, consider learning more from our article on the best Java courses.

In polymorphism, objects having different internal structures can share the same external interface; it means that a class of operation may be accessed in the same manner even though actions with each operation may differ. Inheritance extensively uses the concept of polymorphism. 

Polymorphism can be achieved in two ways:

Method Overloading 

It is possible to create methods with the same name but different parameter lists and different definitions. This is called method overloading. Method overloading is required when objects are required to perform similar tasks but using different input parameters.

When we call a method in an object, Java matches up the method name first and then the number and type of parameters to decide which definition to execute. 

Method overloading is achieved in three ways:

On the Basis of 

Example 

Number of Parameters 

times(int, int)
times(int, int, int)

Data Types of Parameters 

times(int, int)
times(int, float)

The Sequence of Data Types of Parameters 

times(int, float)
times(float, int)

Example Code: 

The code below demonstrates the concept of method overloading.

class CircleArea 
{
 double area(double x)
 {
  return 3.14 * x;
 }
}

class SquareArea 
{
 int area(int x)
 {
  return x * x;
 }
}

class RectangleArea 
{
 int area(int x, int y)
 {
  return x * y;
 }
}

class TriangleArea 
{
 int area(int y, int x)
 {
  return (y * x)/2;
 }
}

class Overloading 
{
 public static void main(String args[])
 {
  CircleArea ca = new CircleArea();
  SquareArea sa = new SquareArea();
  RectangleArea ra = new RectangleArea();
  TriangleArea ta = new TriangleArea();

  System.out.println("Circle area = "+ ca.area(1));
  System.out.println("Square area = "+ sa.area(2));
  System.out.println("Rectangle area = "+ ra.area(3,4));
  System.out.println("Triangle area = "+ ta.area(6,3));
 }
}

Method Overriding 

A method defined in the superclass is inherited by its subclass and is used by the objects created by the subclass. However, there may be occasions when an object should respond to the same method but behave differently when that method is called, which means a method defined in the superclass is overridden.

Overriding is achieved by defining a method in the subclass that has the same name, the same arguments, and the same return type as a method in the superclass. So, when the method is called, the method defined in the subclass is invoked and executed instead of the one in the superclass. 

Example Code: 

The code below demonstrates the concept of method overriding.

class Shape 
{
 void draw()
 {
  System.out.println("Mention shape here");
 }

 void  numberOfSides()
 {
  System.out.println("side = 0");
 }
}

class Circle extends Shape 
{
 void draw()
 {
  System.out.println("CIRCLE ");
 }

 void numberOfSides()
 {
  System.out.println("side = 0 "); 
 }
}

class Box extends Shape 
{
 void draw()
 {
  System.out.println("BOX ");
 }

 void numberOfSides()
 {
  System.out.println("side= 6"); 
 }
}

class Triangle extends Shape 
{
 void draw()
 {
  System.out.println("TRIANGLE ");
 }

 void numberOfSides()
 {
  System.out.println("side = 3 ");
 }
}

class Overriding 
{
 public static void main (String args[])
 {
  Circle c = new Circle();
  c.draw();
  c.numberOfSides();

  Box b = new Box();
  b.draw();
  b.numberOfSides();

  Triangle t = new Triangle();
  t.draw();
  t.numberOfSides();
 }
}

Dynamic Binding 

Binding is the process of linking a procedure call to the code to be executed in response to the call. It means that the code associated with the given procedure call is not known until the time of the call at runtime. It is associated with inheritance and polymorphism. 

Message Communication 

Objects communicate with each other in OOPs The process of programming in case of OOP consists of the following:

  • Creating classes defining objects and their behavior.
  • Creating objects 
  • Establishing communication between objects.

The Network of Objects Communicating with Each Other 

Specifying the object name, the method name, and the information to be sent is involved in message passing. 

For Example, consider the statement.

Objects can be created or destroyed as they have a life cycle. It allows communication between the objects until the objects are alive. 

Java Programming Masterclass updated to Java 17

Benefits of OOPs Concept in Java

  • Inheritance eliminates redundant code and enables reusability. 
  • As Message passing allows communication with objects, this presents writing code from scratch every time. It is thus saving development time and higher productivity. 
  • Partitions work in a project based on classes and objects.
  • Systems up-gradation is easy.

Applications of OOPs Concept in Java

  • Real-time systems
  • Simulation and modeling 
  • Object-oriented databases
  • Hypertext and Hypermedia
  • AI and expert systems
  • Neural networks and parallel programming 
  • Automation systems

Summary 

Sometimes it helps to consider OOPs concepts in Java like a state-of-the-art toolbox. . . because that's basically what it is. Java's all about tools and toolkits. The tools are like the 'objects', and the toolkits, where each kind of tool belongs, are the 'classes'. When you need to fix something, you pull out a specific tool (object) from its toolkit (class).

In simple terms, Java is an object-oriented programming language. Its concepts are like a trusty toolbox, designed to help you build things in the digital world with ease, precision, and creativity. It's got all the cool gadgets to make sure whatever you build is solid and works smoothly!

People are also reading:

By Simran Kaur Arora

Simran works at Hackr as a technical writer. The graduate in MS Computer Science from the well known CS hub, aka Silicon Valley, is also an editor of the website. She enjoys writing about any tech topic, including programming, algorithms, cloud, data science, and AI. Traveling, sketching, and gardening are the hobbies that interest her.

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

Thanks for subscribing! Look out for our welcome email to verify your email and get our free newsletters.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments