OOPs Concepts in Java with Examples: The 2024 Guide
OOP, or Object-Oriented Programming, is a programming paradigm used for software development. It is the most standardized way to code and is taught to all developers in the educational field. It structures a program into simple and reusable classes, which play a crucial role in creating individual instances of objects.
There are many object-oriented programming languages, like JavaScript, C++, Python, and Java. In this blog, we will discuss the OOPs concepts in Java, their examples, and more. Briefly, we will focus on the concepts beneficial for developers.
What is OOPs Concept In Java?
Object Oriented Programming (OOPs) is computer programming that models software around data and objects. It is a data field that consists of unique attributes and behaviors. It works well with programs that are complex, large, and constantly need an update. It simplifies software development and maintenance.
Here’s a brief explanation of the basic concepts of OOPs in Java:
- Inheritance: It allows one to acquire and inherit the properties of an existing class to a new class, i.e., from a parent class to a child class.
- Abstraction: Abstraction hides the implementation used from the user and only shows the essential information. It reduces the complexity, eases the maintenance burden, and increases confidentiality and security.
- Encapsulation: This concept is a mechanism that allows binding functions and data of a class into an entity. It provides security by protecting the data and functions from outside interference and misuse.
- Polymorphism: This concept is a combination of two words: poly means many, and morph means form. It allows the programmer to create methods with the same name but different methods. It makes a clean and resilient code.
Also Read: What is Java
List of OOPs Concepts in Java
1. OOPs Objects in Java
Instances of a class created from a class in Java and other languages are known as objects. The objects are always corresponding to the things found in the real world. They are also called the run-time entity of the world. These objects contain properties that make data useful and can be both physical and logical.
To create an object, specify the class name followed by the object name. In the program below, MyBook is the class.
public class MyBook {
int value = 10;
public static void main(String[] args) {
MyBook myObj = new MyBook();
System.out.println(myObj.value);
}
}
In this program,
- [ int value 10 ] declares the instance variable of ‘value’ and sets its value to 10.
- [ MyBook myObj new MyBook() ] creates a new MyBook object, assigns it to the variable myObj, allocates memory with the keyword new, and initializes it with the constructor MyBook().
- [ System.out.println(myObj.value) ] returns the value of the instance variable ‘value’ and prints it to the console.
- [public static void main(String[] args] serves as the entry point to the program.
2. OOPs Classes in Java
Object constructors used for creating objects are known as classes. A collection of objects is also known as a class. They are logical quantities and do not consume any space in the memory. They are also called a template of an object as they have members like fields, methods, and constructors. They have both static and instance initializers.
The class declaration consists of the following components:
- Modifiers: These can be public or default access.
- Class name: The initial letters.
- Superclass: This can only extend to one parent.
- Interfaces: More than one interface can be implemented.
- Body: It is surrounded by braces.
The variables defined within a class are called instance variables. The methods defined within a class are called members.
For example:
public class ClassName
{
// Instance variables
type instanceVariable1;
type instanceVariable2;
// ...
type instanceVariableN;
// Method 1
type methodName1(parameterList) {
// Method body
}
// ...
// Method N
type methodNameN(parameterList) {
// Method body
}
}
- [ ClassName ] declares the name of the class.
- [ type instanceVariable1,…,type instanceVariableN ] represent the instance variables or attributes of the class. ‘Type’ word represents the data type.
- [ type methodName1(parameterList) (// Method body) ] represent the method body containing logic and parameter list.
3. Abstraction in Java
Abstraction is the process that only displays the required and important information and hides the unnecessary fluff. Filtering out only the required data from a large amount reduces the complexity and increases efficiency.
There are abstract classes and abstract methods. The purpose of an abstract class is to declare one or more abstract methods. The abstract method has a method definition but not a method implementation. The method is used when one or more subclasses are presently performing different tasks using different implementations. Once the object is modeled using data abstraction, the same sets can be used in various applications. To get a more in-depth understanding of Java, you can opt for a Core Java course and build your career as a developer.
Let’s understand abstraction with an example.
If we are to admit a student into an institution, we might require some basic information about the student. This information can include their name, class, address, date of birth, father’s name, and mother’s name. Now to fill out the application form, we might not need all the information we collected. Hence, the fetching, removing, filtering, and selection of the required data will be known as abstraction in the OOPs Java.
For example:
abstract class Animal
{
public abstract void makeSound();
}
class Lion extends Animal {
public void makeSound() {
System.out.println("The lion roars.");
}
public static void main(String[] args)
{
Animal animal = new Lion();
animal.makeSound();
}
}
- This program defines the abstract class name called ‘Animal’ with an abstract method name ‘makeSound ()’.
- ‘Lion’ is the child class of the parent class ‘Animal’. It inherits the same method ‘makeSound ()’ from the parent class and prints the animal sound as output, ‘The lion roars’ on the console.
- [ Animal animal = new Lion() ] creates an instance of the ‘Lion’ class and assigned to the ‘Animal’ class type reference variable ‘animal’.
4. Inheritance in Java
Inheritance is the method in which one object acquires the properties of another object. It supports hierarchical classification. With the help of this method, we can create new classes based on the existing classes. This concept also represents the parent-child relationship, as new fields are created by reusing the existing fields.
The following are the common types of inheritance:
A. Single Level
There is parent class and child class.
Syntax-
class X {
// ...
}
class Y extends X {
// ...
}
In this example, class Y (child class) inherits the properties from class Z (parent class).
B. Multilevel
There is class that derives its attributes from another class, which is also derived from another class. It means there is two or more parental classes.
Syntax-
class X {
….
}
class Y extends class X {
….
}
class Z extends class Y {
…
}
C. Hierarchical Level
Two or more child classes have one parental class.
Syntax-
class X {
…
}
class Y extends class X {
..
}
class Z extends class X {
..
}
D. Hybrid
It is a combination of multiple inheritance. There is a superclass and subclasses in this type of inheritance.
Syntax-
// Create a superclass
class Add
{
int my;
int by;
void setMyBy(int x, int y)
{
my = x;
by = y;
}
}
// Create a subclass
class B extends Add
{
int total;
void sum()
{
total = my + by;
}
public static void main(String[] args) {
B subObj = new B();
subObj.setMyBy(12, 15);
subObj.sum();
System.out.println("Total = " + subObj.total);
}
}
Output - Total = 27
Also Read: Java Interview Questions
5. Polymorphism in Java
Polymorphism is the process that performs a single action in different ways. It is used when there are many classes related to each other by inheritance. There are mainly two types of polymorphism: compile-time and run-time.
The concept of polymorphism is often expressed or used as one interface and multiple methods. It reduces complexity and allows the same interface to be used as a general class of action.
Compile-time polymorphism is used when we overload a static method in Java, while the run-time polymorphism is used to call an overridden method.
For example:
public class Bird
{
public void makeSound() {
System.out.println("Birds produce sounds.");
}
}
public class Pigeon extends Bird {
@Override
public void makeSound() {
System.out.println("The pigeon makes a cooing sound.");
}
}
public class Sparrow extends Bird {
@Override
public void makeSound() {
System.out.println("The sparrow emits a chirping sound.");
}
}
In this example, there is a common action makeSound() which is used in different ways to display the sounds of various classes of bird.
6. Encapsulation in Java
Encapsulation is the method used to bind data and code into a single unit keeping it safe from outside inheritance and misuse. The data is hidden from other classes and can only be accessed through the current class’s method. In simple words, the OOPs definition in Java for encapsulation is that it is used to hide the data.
For example:
class Animal
{
private int age;
public int getAge() {
return age;
}
public void setAge(int newAge)
{
this.age = newAge;
}
}
class Main {
public static void main(String[] args)
{
Animal animal = new Animal();
animal.setAge(10);
System.out.println("The age of the animal is: " + animal.getAge());
}
}
Output - The age of the animal is 10
This example uses private field called age, which cannot be accessed outside the class, except by using public methods like getter and setter. This data hiding restricts unauthorized access.
Conclusion
- OOPs is helpful for developers as it provides a standardized way of coding.
- It provides different models like inheritance, abstraction, encapsulation, and polymorphism.
- The concepts in Java are implemented in real-world entities.
- It provides re-usability and flexibility to the functions.
- It makes large and complex codes manageable.
FAQs
The five pillars of Java are:
1. Objects and Classes
2. Abstraction
3. Encapsulation
4. Inheritance
5. Polymorphism
A constructor in Java creates an instance for an object in a class. It must have the same name as the class, no explicit return type, and should not be abstract or static.
The following are the four main features of OOPs.
Encapsulation: It binds or wraps data and code in a single unit and offers data hiding property.
Abstraction: It conceals implementation details and displays functionality without details.
Inheritance: An object inherits properties and attributes from the parent object.
Polymorphism: It is a method that performs the same task in different ways when the object’s class is called. It allows program code reusability.