Object-oriented programming is a programming model that incorporates principles like inheritance, encapsulation, polymorphism, and more.
Simula is widely recognized as the initial object-oriented programming language. A programming model that treats everything as an object is referred to as a pure object-oriented programming language.
Smalltalk is widely recognized as the initial programming language to fully embrace the principles of object-oriented programming.
Java, C#, PHP, Python, and C++ are among the commonly used object-oriented programming languages.
OOPs (Object-Oriented Programming)
Object-oriented programming is designed to model real-world concepts such as objects, classes, abstraction, inheritance, and polymorphism.
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-oriented programming is a methodology or paradigm for designing a program using classes and objects. It simplifies software development and maintenance by providing some concepts:
- Object
- Class
- Inheritance
- Polymorphism
- Abstraction
- Encapsulation
Apart from these concepts, there are some other terms which are used in Object-Oriented design:
- Coupling
- Cohesion
- Association
- Aggregation
- Composition
Object
An object refers to any entity that possesses both state and behavior. This can include items such as chairs, pens, tables, keyboards, bikes, and more, whether they are tangible or conceptual.
An Object is an instantiation of a class, possessing a memory location and occupying memory space. Objects are capable of interacting with each other without needing access to the specifics of the other's data or implementation. The essential factors for interaction are the type of message that can be received and the type of response that can be provided by the objects.
To read more Object in Java
An animal such as a dog can be considered an object in programming due to its attributes such as color, name, breed, and actions such as wagging the tail, barking, and eating.
The primary elements of an object are:
- State: It is embodied in an object's properties. Additionally, it reflects an object's attributes.
- Behavior: An object's methods are a representation of it. Additionally, it represents how an object reacts to other objects.
- Identity: Identity is a special name that gives a thing the ability to communicate with other objects.
- Method: A method is a group of statements that carry out a certain operation and give an outcome. A method can complete a certain task without giving back any results. Methods are regarded as time savers since they enable us to reuse the code without having to type it again. Java differs from languages like C, C++, and Python in that each method needs to be a component of a class.
Example of Object
Example
class Dog {
String name;
void bark() {
System.out.println(name + " says Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog(); // Creating an object
myDog.name = "Rocky"; // Assigning value to the object's field
myDog.bark(); // Calling method on the object
}
}
Output:
Rocky says Woof!
Class
A class is a conceptual unit that serves as a template for creating specific objects. It does not occupy any memory space.
In general, a class declaration includes the following in the order as it appears:
- Modifiers: A class can be public or have default access.
- class keyword: The class keyword is used to create a class.
- Class name: The name must begin with an initial letter (capitalized by convention).
- Superclass (if any): The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
- Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
- Body: The class body surrounded by braces, { }.
To read more Class Definition in Java
Inheritance
Inheritance occurs when an object inherits all the attributes and methods of a parent object, promoting code reuse and enabling the implementation of runtime polymorphism.
To read more Inheritance in Java
Example of Inheritance
Example
// Superclass (Parent)
class Vehicle {
void start() {
System.out.println("Vehicle is starting...");
}
void stop() {
System.out.println("Vehicle is stopping...");
}
}
// Subclass (Child) - Inherits from Vehicle
class Car extends Vehicle {
void honk() {
System.out.println("Car is honking!");
}
}
public class MainExample {
public static void main(String[] args) {
Car myCar = new Car();
// Calling inherited methods (from Vehicle)
myCar.start();
myCar.stop();
// Calling child class method
myCar.honk();
}
}
Output:
Vehicle is starting...
Vehicle is stopping...
Car is honking!
Polymorphism
Polymorphism refers to the concept of performing a single task in various ways. For instance, this can involve persuading customers using different approaches or creating various shapes like triangles, rectangles, and so on.
To read more Polymorphism in Java
In the Java programming language, polymorphism is implemented through the concepts of method overloading and method overriding.
An additional illustration is vocalizing sounds, such as a cat producing a "meow" or a dog emitting a "woof."
Example of Polymorphism
Example
class Animal {
// Method Overloading (compile-time polymorphism)
void sound() {
System.out.println("An animal makes a sound");
}
void sound(String type) {
System.out.println("Animal sound: " + type);
}
}
class Dog extends Animal {
// Method Overriding (runtime polymorphism)
@Override
void sound(String type) {
System.out.println("Dog barking is: " + type);
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Animal();
Dog d = new Dog();
Animal poly = new Dog();
// Method Overloading
a.sound();
a.sound("Generic");
// Method Overriding
d.sound("Loud");
// Performing the Polymorphism
poly.sound("Soft");
}
}
Output:
An animal makes a sound
Animal sound: Generic
Dog barking is: Loud
Dog barking is: Soft
Abstraction
Abstraction refers to the concept of concealing internal workings and presenting only the outward behavior to users. A classic example is the abstraction of phone call operations, where users are unaware of the underlying technical processes. In Java programming, abstraction is implemented through abstract classes and interfaces.
To read more Abstraction in Java
Example of Abstraction
Example
abstract class Animal {
abstract void makeSound();
// Creating a Concrete method
void breathe() {
System.out.println("Animal is breathing...");
}
}
// Concrete subclass
class Dog extends Animal {
// implementation for an abstract method
@Override
void makeSound() {
System.out.println("Dog barking");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.breathe();
myDog.makeSound();
}
}
Output:
Animal is breathing...
Dog barking
Encapsulation
Encapsulating code and data together forms a unified unit, a concept known as encapsulation. To illustrate, envision a capsule enveloping various medications within.
Encapsulation is exemplified in Java through the concept of a Java class. A Java bean demonstrates complete encapsulation as it contains private data members.
To read more Encapsulation in Java
Example of Abstraction
Example
class Student {
// Private data members
private String name;
// Setter method
public void setName(String name) {
this.name = name;
}
// Getter method
public String getName() {
return name;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
// Setting value using setter
s.setName("John");
// Getting value using getter
System.out.println("Student Name: " + s.getName());
}
}
Output:
Student Name: John
Coupling
Coupling is the connection, understanding, or reliance on another class. This occurs when classes have awareness of each other. Strong coupling exists when a class possesses knowledge about another class. In Java, we utilize private, protected, and public modifiers to indicate the visibility level of a class, method, and field. Interfaces can be employed for a looser coupling since they lack a concrete implementation.
To read more Loose Coupling in Java
Cohesion
Cohesion is a measure of how well a component focuses on executing a singular, clearly defined operation. A method with high cohesion is dedicated to performing a single, well-defined task. Conversely, a method with low cohesion divides its task into multiple unrelated parts. For instance, the java.io package demonstrates high cohesion as it encompasses classes and interfaces related to input/output operations. On the other hand, the java.util package showcases low cohesion as it includes classes and interfaces that are not closely related.
To read more Cohesion in Java
Association
The association represents the relationship between the objects. Here, one object can be associated with one object or many objects. There can be four types of association between the objects:
- One-to-One
- One to Many
- Many to One
- Many-to-Many
In a country, there is a relationship where one prime minister can lead many ministers (one-to-many), while many Members of Parliament (MPs) can be represented by one prime minister (many-to-one). Additionally, multiple ministers can oversee various departments in a many-to-many relationship.
Note: The association can be unidirectional or bidirectional.
To read more Association in Java
Aggregation
Aggregation serves as a means to establish an Association, denoting a relationship in which one object includes other objects as part of its state. This signifies a less strong bond between objects and is commonly known as a HAS-A relationship in the context of Java, akin to how inheritance signifies an IS-A relationship. It stands as an alternative method for object reuse.
To read more Aggregation in Java
Composition
Composition is another method to establish Association in object-oriented programming. It signifies the connection in which one object encompasses other objects within its state. This establishes a close link between the encompassing object and the subordinate object. In this scenario, the objects cannot exist independently. Deleting the parent object will consequently lead to the automatic deletion of all child objects.
To read more Composition in Java
Advantages of OOP Over Procedure-Oriented Programming Language
- OOPs make development and maintenance easier, whereas in a procedure-oriented programming language, it is not easy to manage if the code grows as the project size increases.
- OOP provides data hiding, whereas in a procedure-oriented programming language, global data can be accessed from anywhere.
- OOPs provide the ability to simulate real-world events much more effectively. We can provide the solution to real-world problems if we use an Object-Oriented Programming language.
What is the difference between an object-oriented programming language and an object-based programming language?
An object-based programming language encompasses all aspects of OOP except for Inheritance. JavaScript and VBScript serve as prime illustrations of object-based programming languages.
Example
// Java program for demonstrating the features and functionalities of OOP concepts in Java.
class Animal {
private String name;
// Constructor
public Animal(String name) {
this.name = name;
}
// Encapsulation: Getter method
public String getName() {
return name;
}
// Polymorphism: Overridden method
public void makeSound() {
System.out.println("Some sound");
}
}
// Derived class (Inheritance)
class Dog extends Animal {
// Constructor
public Dog(String name) {
super(name);
}
// Polymorphism: Overriding method
@Override
public void makeSound() {
System.out.println("Woof");
}
}
// Derived class (Inheritance)
class Cat extends Animal {
// Constructor
public Cat(String name) {
super(name);
}
// Polymorphism: Overriding method
@Override
public void makeSound() {
System.out.println("Meow");
}
}
public class Main{
public static void main(String[] args) {
// Creating objects of the Dog and Cat classes
Dog dog = new Dog("Buddy");
Cat cat = new Cat("Whiskers");
// Accessing methods of the base class through objects of derived classes
System.out.println("Dog name: " + dog.getName());
dog.makeSound();
System.out.println("Cat name: " + cat.getName());
cat.makeSound();
}
}
Output:
Dog name: Buddy
Woof
Cat name: Whiskers
Meow