Four Main Object Oriented Programming Concepts of Java
Last Updated :
09 Jul, 2024
Object-oriented programming generally referred to as OOPS is the backbone of java as java is not a purely object oriented language but it is object oriented language. Java organizes a program around the various objects and well-defined interfaces. There are four pillars been here in OOPS which are listed below. These concepts aim to implement real-world entities in programs.
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
Abstraction
Abstraction is a process of hiding implementation details and exposing only the functionality to the user. In abstraction, we deal with ideas and not events. This means the user will only know “what it does” rather than “how it does”.
There are two ways to achieve abstraction in Java:
- Abstract class (0 to 100%)
- Interface (100%)
Real-Life Example: A driver will focus on the car functionality (Start/Stop -> Accelerate/ Break), he/she does not bother about how the Accelerate/ brake mechanism works internally. And this is how the abstraction works.
Certain key points should be remembered regarding this pillar of OOPS as follows:
- The class should be abstract if a class has one or many abstract methods
- An abstract class can have constructors, concrete methods, static method, and final method
- Abstract class can't be instantiated directly with the new operator. It can be possible as shown in pre tag below:
A b = new B();
- The child class should override all the abstract methods of parent else the child class should be declared with abstract keyword.
Example:
Java
// Abstract class
public abstract class Car {
public abstract void stop();
}
// Concrete class
public class Honda extends Car {
// Hiding implementation details
@Override public void stop()
{
System.out.println("Honda::Stop");
System.out.println(
"Mechanism to stop the car using break");
}
}
public class Main {
public static void main(String args[])
{
Car obj
= new Honda(); // Car object =>contents of Honda
obj.stop(); // call the method
}
}
Encapsulation
Encapsulation is the process of wrapping code and data together into a single unit.
Real-Life Example:
A capsule which is mixed of several medicines. The medicines are hidden data to the end user.
In order to achieve encapsulation in java follow certain steps as proposed below:
- Declare the variables as private
- Declare the setters and getters to set and get the variable values
Note: There are few advantages of encapsulation in java as follows:
- Control Over Data: We can write the logic in the setter method to not store the negative values for an Integer. So by this way we can control the data.
- Data Hiding: The data members are private so other class can't access the data members.
- Easy to test: Unit testing is easy for encapsulated classes
Example:
Java
// A Java class which is a fully encapsulated class.
public class Car {
// private variable
private String name;
// getter method for name
public String getName(){
return name;
}
// setter method for name
public void setName(String name){
this.name = name;
}
}
// Java class to test the encapsulated class.
public class Test {
public static void main(String[] args)
{
// creating instance of the encapsulated class
Car car
= new Car();
// setting value in the name member
car.setName("Honda");
// getting value of the name member
System.out.println(car.getName());
}
}
Inheritance
Inheritance is the process of one class inheriting properties and methods from another class in Java. Inheritance is used when we have is-a relationship between objects. Inheritance in Java is implemented using extends keyword.
Real-life Example:
The planet Earth and Mars inherits the super class Solar System and Solar system inherits the Milky Way Galaxy. So Milky Way Galaxy is the top super class for Class Solar System, Earth and Mars.
Let us do discuss the usage of inheritance in java applications with a generic example before proposing the code. So consider an example extending the Exception class to create an application-specific Exception class that contains more information like error codes. For example NullPointerException.
There are 5 different types of inheritance in java as follows:
- Single Inheritance: Class B inherits Class A using extends keyword
- Multilevel Inheritance: Class C inherits class B and B inherits class A using extends keyword
- Hierarchy Inheritance: Class B and C inherits class A in hierarchy order using extends keyword
- Multiple Inheritance: Class C inherits Class A and B. Here A and B both are superclass and C is only one child class. Java is not supporting Multiple Inheritance, but we can implement using Interfaces.
- Hybrid Inheritance: Class D inherits class B and class C. Class B and C inherits A. Here same again Class D inherits two superclass, so Java is not supporting Hybrid Inheritance as well.
Example:
Java
// super class
class Car {
// the Car class have one field
public String wheelStatus;
public int noOfWheels;
// the Car class has one constructor
public Car(String wheelStatus, int noOfWheels)
{
this.wheelStatus = wheelStatus;
this.noOfWheels = noOfWheels;
}
// the Car class has three methods
public void applyBrake()
{
wheelStatus = "Stop";
System.out.println("Stop the car using break");
}
// toString() method to print info of Car
public String toString()
{
return ("No of wheels in car " + noOfWheels + "\n"
+ "status of the wheels " + wheelStatus);
}
}
// sub class
class Honda extends Car {
// the Honda subclass adds one more field
public Boolean alloyWheel;
// the Honda subclass has one constructor
public Honda(String wheelStatus, int noOfWheels,
Boolean alloyWheel)
{
// invoking super-class(Car) constructor
super(wheelStatus, noOfWheels);
this.alloyWheel = alloyWheel;
}
// the Honda subclass adds one more method
public void setAlloyWheel(Boolean alloyWheel)
{
this.alloyWheel = alloyWheel;
}
// overriding toString() method of Car to print more
// info
@Override public String toString()
{
return (super.toString() + "\nCar alloy wheel "
+ alloyWheel);
}
}
// driver class
public class Main {
public static void main(String args[])
{
Honda honda = new Honda("stop", 4, true);
System.out.println(honda.toString());
}
}
Polymorphism
Polymorphism is the ability to perform many things in many ways. The word Polymorphism is from two different Greek words- poly and morphs. “Poly” means many, and “Morphs” means forms. So polymorphism means many forms. The polymorphism can be present in the case of inheritance also. The functions behave differently based on the actual implementation.
Real-life Example:
A delivery person delivers items to the user. If it's a postman he will deliver the letters. If it's a food delivery boy he will deliver the foods to the user. Like this polymorphism implemented different ways for the delivery function.
There are two types of polymorphism as listed below:
- Static or Compile-time Polymorphism
- Dynamic or Run-time Polymorphism
Static or Compile-time Polymorphism when the compiler is able to determine the actual function, it’s called compile-time polymorphism. Compile-time polymorphism can be achieved by method overloading in java. When different functions in a class have the same name but different signatures, it’s called method overloading. A method signature contains the name and method arguments. So, overloaded methods have different arguments. The arguments might differ in the numbers or the type of arguments.
Example 1: Static Polymorphism
Java
public class Car{
public void speed() {
}
public void speed(String accelerator) {
}
public int speed(String accelerator, int speedUp) {
return carSpeed;
}
}
Dynamic or Run-time Polymorphism Dynamic (or run-time) polymorphism occurs when the compiler is not able to determine at compile-time which method (superclass or subclass) will be called. This decision is made at run-time. Run-time polymorphism is achieved through method overriding, which happens when a method in a subclass has the same name, return type, and parameters as a method in its superclass. When the superclass method is overridden in the subclass, it is called method overriding.
Example 2: Dynamic Polymorphism
Java
import java.util.Random;
class DeliveryBoy {
public void deliver() {
System.out.println("Delivering Item");
}
public static void main(String[] args) {
DeliveryBoy deliveryBoy = getDeliveryBoy();
deliveryBoy.deliver();
}
private static DeliveryBoy getDeliveryBoy() {
Random random = new Random();
int number = random.nextInt(5);
return number % 2 == 0 ? new Postman() : new FoodDeliveryBoy();
}
}
class Postman extends DeliveryBoy {
@Override
public void deliver() {
System.out.println("Delivering Letters");
}
}
class FoodDeliveryBoy extends DeliveryBoy {
@Override
public void deliver() {
System.out.println("Delivering Food");
}
}
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read