O.O.P (Object Oriented Programming) or OOPs !! in Java…
By: Suyash Thonte
Tags: Oops Interview Questions, Object Oriented, Oops Concepts, Java Oop, Java

Not the word Ooops!! It’s O.O.P’s (i.e Object Oriented Programming)!!!

HEY ! So in this post I will be highlighting and describing the OOPs concepts in Java and where they get applied in a Java Program.

Before starting with OOPs concepts let us see the 2 programming paradigms namely :

Procedural Oriented (More focus on procedure rather than data.) Object Oriented (More focus on data rather than procedure.)

So Structured / Procedural Programming lacks whenever programs grow larger and complex. So to manage the increasing complexity , that’s when Object-Oriented Programming comes into the scene.

Object Oriented Programming :

Object Oriented Programming is a programming methodology that helps organise complex programs using the concept of Objects that interact with the real world and implementing concepts like Abstraction, Polymorphism, Encapsulation, Inheritance,etc.

OOPs Concepts :

Class Object Abstraction Encapsulation Inheritance Polymorphism

The last 4 (i.e Abstraction, Encapsulation, Inheritance and Polymorphism) are also referred to as the 4 Pillars of Object Oriented Programming or OOPs.

Abstraction ~~~~~~~~~~~ Encapsulation ~~~~~~~~~~~ Inheritance ~~~~~~~~~~~~ Polymorphism

1. Class :

Class is a logical construct which defines the state, behaviour and identity of an object. So basically it is a blueprint which contains elements or data which have certain common traits or nature , i.e , they perform same functions or posses similar features. Speaking in other words, Class can be visualised as a mold which stamps out the object (in the form of structure and behaviour) in its own shape.

Class may consist of :

Class name

Blocks

Variables (also called instance variables)

Methods

Constructors

Interface

2. Object

Object is a physical entity in an object-oriented system, i.e it physically exists !! An object can represent a person, a bank account, a place, a table of data. It may also represent user-defined data types like lists and vectors.

As I mentioned earlier, class is like a mold which stamps out an object, so this stamped out object has the structure and behaviour as designed by the class, hence objects are also known as instances of a class.

Hence object has got 2 characteristics i.e a structure or a state and a behaviour, below is the example for these :

Object: House

State: Address, Color, Area

Behaviour: Open door, close door

So if I had to write a class based on these 2 characteristics of the House, It will be like : State will be considered as instance variables and Behaviours as methods of the class. Below will be the code :

class House {

String address;

String color;

double are;

void openDoor() {

//Write code here

}

void closeDoor() {

//Write code here

}

...

...

}

3. Abstraction

Abstraction is the concept of hiding implementation details from the user. Humans manage complexity through abstraction, for e.g Let’s assume a case of mobile phone. When user buys a phone, he doesn’t see how that phone had developed but sees only the working of phone such as calling, music, videos, etc. while inner implementations of cell phone remains hidden. This is called abstraction.

Abstraction can be achieved through 2 ways :

Abstract class :

Abstract class is used when you currently don’t know the implementation of a class or method, i.e. hidden part that user can’t see. In abstract class, atleast one method must be declared as abstract consisting of several other concrete methods. Through abstract class, we achieve 0 - 100 % 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();

}

}

Interface :

Interface in Java is a blueprint of a class or you can say it is a collection of abstract methods and static constants. In an interface, each method is public and abstract but it does not contain any constructor. Along with abstraction, interface also helps to achieve multiple inheritance in Java. So unlike Abstract class, every method in interface is abstract or is a group of methods with empty bodies. Through in Interface, we achieve 100 % abstraction.

// Interface

interface Animal {

public void animalSound(); // interface method (does not have a body)

public void sleep(); // interface method (does not have a body)

}



// Pig "implements" the Animal interface

class Pig implements Animal {

public void animalSound() {

// The body of animalSound() is provided here

System.out.println("The pig says: wee wee");

}

public void sleep() {

// The body of sleep() is provided here

System.out.println("Zzz");

}

}



class MyMainClass {

public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound();

myPig.sleep();

}

}

4. Encapsulation

Encapsulation, as the name suggests is the process of encapsulating or capsulating your code. It is a mechanism where you bind your data and code together into a single unit. Also it means that ensuring that “sensitive” data is hidden from users. WHAT ?? What does this mean? So, lets take an example of medical capsule, in which the medicine powder or the drug is always safe and wrapped up inside the capsule, similiarly, the methods and instance variables are safe inside a class and well hidden due to encapsulation.

Methods and variables safe inside the class capsule

Encapsulation can be achieved by :

Declaring the instance variables as private. Providing getter and setter methods to access and modify the private variables.

public class Person {

private String name; // private = restricted access



// Getter

public String getName() {

return name;

}



// Setter

public void setName(String newName) {

this.name = newName;

}

} public class MyClass {

public static void main(String[] args) {

Person myObj = new Person();

myObj.setName("John"); // Set the value of the name variable to "John"

System.out.println(myObj.getName());

}

}



// Outputs "John"

5. Inheritance

There are times when we require the code from the previous program or class and thus hence in Java, it is possible to inherit the attributes and methods from the previous classes or different classes. Thus doing so will ease the reuse of code i.e improving the re-usability and also reducing the complexity of code to a further extent.

So in Inheritance, the new class adopts or inherits all the properties from the another class. Here, the new class or inheriting class is often referred as “sub-class” or “child class” or “base class” and the original class is often termed as “super-class” or “parent class” or “derived class”.

Example of Inheritance : Parent Class and Child Class

But what if there are 2 or more child or sub classes which are required to inherit from the same parent or super class ?? Is it even possible!!

Also if a child class has got all the properties from parent and also has its own features / properties , but these all properties from the child (i.e parent features and its own features) are further required into a new class where they would be required, so is it even possible?? Will there be a grand-child class !!?

Guys don’t panic !!! , all the above conditions are actually possible and these are divided into different types of Inheritance in Java namely :

Single Inheritance

Multi-Level Inheritance

Hierarchical Inheritance

Hybrid Inheritance

1. Single Inheritance : A single subclass inherits the property of a super class.

Single Inheritance (parent -> child)

public class A{

// statements

}

public class B extends A{

// statements

}

2. Multi-level Inheritance : When a class is derived from a class which is also derived from another class. Yes like the Grand-Child Class !! Exactly Ha Ha !!

Multi-level Inheritance (parent -> child -> grandchild)

public class A{

// statements

}

public class B extends A{

// statements

}

public class C extends B{

//statements

}

3. Hierarchical Inheritance : When there are more than one child class inheriting the same parent class, then it is hierarchical.

Hierarchical Inheritance (same parent -> 2 or more children)

public class A{

// statements

}

public class B extends A{

//statements

}

public class C extends A{

// statements

}

public class D extends A{

// statements

}

Multiple Inheritance : Wait !!! What ??? Where does this come from now ? You would be confused that I mentioned only 4 types and this type is not even mentioned in the above list. Exactly!, it actually doesn’t exist in Java. But it exists in other languages say C / C++. So here I am referring to this type so as to get you guys understand the last type. ~ In multiple inheritance, one direct sub-class inherits two or more than two direct super classes. But in Java, Multiple Inheritance is not allowed as it is possible that 2 or more direct super-classes may have the same methods and variables and hence when child calls the parent class’s method, the JVM will get confused whether which method to call and hence will output an error. But To solve this problem, concept of Interface was introduced. In Java, multiple interface is allowed but multiple inheritance is not allowed.

public class A{

// statements

}

public class B{

// statements

}

public class C extends A, B{

// statements

}

4. Hybrid Inheritance : So Hybrid Inheritance is actually the combination of Multi-level and Multiple Inheritance. But we know that multiple inheritance is not allowed in Java then how come it’s possible to apply for Hybrid inheritance?

The answer is simple, as I mentioned earlier that multiple inheritance is not allowed but I did say that though multiple interface is allowed, so yess!, Hybrid can be achieved through use of interfaces.

public class A{

// statements

}

public class B extends A{

// statements

}

public class C extends A{

// statements

}

public class D extends B, C{

// statements

}

Hybrid Inheritance (parent -> 2 or more children -> new child of all the previous children)

6. Polymorphism

Polymorphism simple means ‘means many forms’ as the word suggests - ‘poly’ meaning “many” and ‘morph’ meaning “form”.

Got Confused ??

Let’s see a real life example : What say Cricket !!

Let’s say there is a Bowler Class and it is a parent which contains a bowlingMethod() and there are different child classes according to types of bowlers in cricket namely - FastPacer, MediumPacer and Spinner and all of them inherit the parent class Bowler Class’s bowlingMethod().

Polymorphism

So in the picture above, all 3 children are inheriting the method but in each and every respective child class, the implementation of the bowlingMethod() will be different as compared to others.

So you see, the method name is same i.e ‘bowlingMethod’ but its implementation is different for every child class, so that’s it we achieved Polymorphism !!

Polymorphism in Java is of 2 types :

Compile Time Polymorphism : Also known as Static polymorphism or early binding, this can be achieved through Method Overloading which is a process which allows a class to have two or more methods with the same name but 1) the arguments or data types passed to these methods are different and / or 2) the numbers of arguments in these methods are different.

class Addition {

Static int add(int a, int b) //return type int and 2 arguments

{

return a+b;

}

static double add( double a, double b) //return type double

{

return a+b;

}

static int add(int a, int b, int c) //return type int but 3 args

{

return a+b+c;

}

public static void main(String args[])

{

System.out.println(Addition.add(11,11));

System.out.println(Addition.add(12.3,12.6));

System.out.println(Addition.add(11,12,13));

}

}

2. Run Time Polymorphism : Also known as Dynamic polymorphism or late binding, this can be achieved through Method Overriding or dynamic dispatch which is a process of implementing parent class methods in child class with same name or signature or simple overriding the parent class method. So in this way a programmer can run a method in different ways by simply invoking object of that respective class (i.e parent class or child class).

public Class BowlerClass{

void bowlingMethod()

{

System.out.println(“ bowler “);

}

public Class FastPacer{

void bowlingMethod()

{

System.out.println(“ fast bowler “);

}

Public static void main(String[] args)

{

FastPacer obj= new FastPacer();

obj.bowlingMethod();

}

}

// So here, we override the parent class(BowlerClass) method with the child class method by simple creating object for child class and calling the method !!

So in this way, we have finally covered all the OOPs concepts which form the core principles or building blocks of Java. So grasping these OOPs concept is the key to understand how Java works!

Finally we have come to an end !! So this was all about OOPs concept in Java. That is it from my end , will meet you guys in my next blog !!

So In this way we covered the OOPs concepts and um... um… um……… Oops! Bye !