OOPs concepts in Java with Examples



Object Oriented programming is a programming style which is associated with the concepts like 
Class
Object
Inheritance
Encapsulation
Abstraction
Polymorphism

It's based on the concept of “objects” that contain data and methods.
It works on the principle that objects are the most important part of your program. 
It allows users to create the OBJECTS that they want and then create METHODS to handle those objects. 
Manipulating these objects to get results is the goal of Object Oriented Programming.
Simula is considered as the first object-oriented programming language.
Smalltalk is considered as the first truly object-oriented programming language.

Programming languages can be classified into 3 primary types:
A. Unstructured Programming Languages: The most primitive of all programming languages having sequentially flow of control. Code is repeated through out the program
B. Structured Programming Languages: Has non-sequentially flow of control. Use of functions allows for re-use of code.
C. Object Oriented Programming: Combines Data & Action Together.

1. Class:



Collection of objects is called class. It is a logical entity.
A class in Java is a blueprint which includes all your data and you can create as many objects as you like.
A class contain fields(variables) and methods to describe the behavior of an object.

For example, if you had a Class called “Cars” then
Objects - Mercedes, BMW, Toyota, etc.
Properties(data) - price, speed.
Methods - driving, reverse, braking etc.

Another example,  create a class "Website"
This is just a blueprint, it does not represent any website, however using this we can create Website objects (or instances) that represents the websites. We have created two objects, while creating objects we provided separate properties to the objects using constructor.

public class Website {
   //fields (or instance variable)
   String webName;
   int webAge;

   // constructor
   Website(String name, int age){
      this.webName = name;
      this.webAge = age;
   }
   public static void main(String args[]){
      //Creating objects
      Website obj1 = new Website("beginnersbook", 5);
      Website obj2 = new Website("google", 18);

     //Accessing object data through reference
     System.out.println(obj1.webName+" "+obj1.webAge);
     System.out.println(obj2.webName+" "+obj2.webAge);
   }
}

What is a Constructor?
Constructor looks like a method but it is in fact not a method. It’s name is same as class name and it does not return any value.

MyClass obj = new MyClass();

If you look at the right side of this statement, we are calling the default constructor of class myClass to create a new object (or instance).

A constructor can perform any action, but constructors are designed to perform initializing actions, such as initializing the data fields of objects.

2. Object:
An object can be defined as an instance of a class, and there can be multiple instances of an object in a program.

An object contains both the data and the function, which operates on the data.
An object is a bundle of data and its behaviour(often known as methods).

For example, chair, bike, marker, pen, table, car, etc.

Objects have two characteristics: They have states and behaviors.
Examples of states and behaviors

Example 1:
Object: House
State: Address, Color, Area
Behavior: Open door, close door




3. Inheritance:
The process by which one class acquires the properties and functionalities of another class is called inheritance.
Inheritance provides the idea of re-usability of code.
Each sub class defines only those features that are unique to it, rest of the features can be inherited from the parent class.



As we can see in the image, a child inherits the properties from his father. Similarly, in Java, there are two classes:

a. Parent class ( Super or Base class)

b. Child class (Subclass or Derived class )

A class which inherits the properties is known as Child Class whereas a class whose properties are inherited is known as Parent class.

Note: The biggest advantage of Inheritance is that the code in base class need not be rewritten in the child class.
The variables and methods of the base class can be used in the child class as well.

Syntax: Inheritance in Java
To inherit a class we use extends keyword. Here class A is child class and class B is parent class.

class A extends B
{
}

Inheritance Example,
In this example, we have a parent class Teacher and a child class MathTeacher.
Here we have college name, designation and does() method that is common for all the teachers, thus MathTeacher class does not need to write this code, the common data members and methods can inherited from the Teacher class.

class Teacher {
   String designation = "Teacher";
   String college = "Beginnersbook";
   void does(){
System.out.println("Teaching");
   }
}
public class MathTeacher extends Teacher{
   String mainSubject = "Maths";
   public static void main(String args[]){
      MathTeacher obj = new MathTeacher();
      System.out.println(obj.college);
      System.out.println(obj.designation);
      System.out.println(obj.mainSubject);
      obj.does();
   }
}

Output:
Beginnersbook
Teacher
Maths
Teaching

Inheritance is further classified into 4 types:


i) Single Inheritance:

In single inheritance, one class inherits the properties of another. It enables a derived class to inherit the properties and behavior from a single parent class. This will in turn enable code reusability as well as add new features to the existing code.

Here, Class A is your parent class and Class B is your child class which inherits the properties and behavior of the parent class.

Let’s see the syntax for single inheritance:
Class A
{
---
}
Class B extends A {
---
}

ii) Multilevel Inheritance:

When a class is derived from a class which is also derived from another class, i.e. a class having more than one parent class but at different levels, such type of inheritance is called Multilevel Inheritance.

If we talk about the flowchart, class B inherits the properties and behavior of class A and class C inherits the properties of class B. Here A is the parent class for B and class B is the parent class for C. So in this case class C implicitly inherits the properties and methods of class A along with Class B. That’s what is multilevel inheritance.

Let’s see the syntax for multilevel inheritance in Java:
Class A{
---
}
Class B extends A{
---
}
Class C extends B{
---
}

iii) Hierarchical Inheritance:

When a class has more than one child classes (sub classes) or in other words, more than one child classes have the same parent class, then such kind of inheritance is known as hierarchical.

If we talk about the flowchart, Class B and C are the child classes which are inheriting from the parent class i.e Class A.

Let’s see the syntax for hierarchical inheritance in Java:
Class A{
---
}
Class B extends A{
---
}
Class C extends A{
---
}

iv) Hybrid Inheritance(Multiple Inheritance):

Most of the new OO languages like Small Talk, Java, C# do not support Multiple inheritance. Multiple Inheritance is supported in C++
Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance. 
Since multiple inheritance is not supported in Java as it leads to ambiguity, so this type of inheritance can only be achieved through the use of the interfaces. 

If we talk about the flowchart, class A is a parent class for class B and C, whereas Class B and C are the parent class of D which is the only child class of B and C.

4. Encapsulation:
Encapsulation simply means binding behavior(methods) and variables together. If you are creating class, you are doing encapsulation.

Encapsulation is a mechanism where you bind your data and code together as a single unit. 
It also means to hide your data in order to make it safe from any modification. What does this mean? 

The best way to understand encapsulation is to look at the example of a medical capsule, where the drug is always safe inside the capsule. Similarly, through encapsulation the methods and variables of a class are well hidden and safe.

We can achieve encapsulation in Java by:
  • Declaring the variables of a class as private.
  • Providing public setter and getter methods to modify and view the variables values.
Let us look at the code below to get a better understanding of encapsulation:
public class Employee {
 private String name;
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public static void main(String[] args) {
 }
}

Let us try to understand the above code. I have created a class Employee which has a private variable name. We have then created a getter and setter methods through which we can get and set the name of an employee. Through these methods, any class which wishes to access the name variable has to do it using these getter and setter methods.

So what is the benefit of encapsulation in java programming:
Well, at some point of time, if you want to change the implementation details of the class, you can freely do so without affecting the classes that are using it.

5. Abstraction:

Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user. 
For example, when you login to your bank account online, you enter your user_id and password and press login, what happens when you press login, how the input data sent to server, how it gets verified is all abstracted away from the you.

If you look at the image above, whenever we get a call, we get an option to either pick it up or just reject it. But in reality, there is a lot of code that runs in the background. So you don’t know the internal processing of how a call is generated, that’s the beauty of abstraction. Therefore, abstraction helps to reduce complexity. 

You can achieve abstraction in two ways:
a) Abstract Class
Abstract class: Abstract class in Java contains the ‘abstract’ keyword. Now what does the abstract keyword mean? If a class is declared abstract, it cannot be instantiated, which means you cannot create an object of an abstract class. Also, an abstract class can contain abstract as well as concrete methods.
Note: You can achieve 0-100% abstraction using abstract class.

To use an abstract class, you have to inherit it from another class where you have to provide implementations for the abstract methods there itself, else it will also become an abstract class.
Abstract class Mobile {   // abstract class mobile
Abstract void run();      // abstract method

b) Interface
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.
Note: You can achieve 100% abstraction using interfaces.

6. Polymorphism:

When one task is performed by different ways i.e. known as polymorphism.
Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means forms. 
In java, we use method overloading and method overriding to achieve polymorphism.
For example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

It is the ability of a variable, function or object to take on multiple forms. In other words, polymorphism allows you define one interface or method and have multiple implementations.

Let’s understand this by taking a real-life example and how this concept fits into Object oriented programming.
Let’s consider this real world scenario in cricket, we know that there are different types of bowlers i.e. Fast bowlers, Medium pace bowlers and spinners. As you can see in the above figure, there is a parent class- BowlerClass and it has three child classes: FastPacer, MediumPacer and Spinner. Bowler class has bowlingMethod() where all the child classes are inheriting this method. As we all know that a fast bowler will going to bowl differently as compared to medium pacer and spinner in terms of bowling speed, long run up and way of bowling, etc. Similarly a medium pacer’s implementation of bowlingMethod() is also going to be different as compared to other bowlers. And same happens with spinner class.
The point of above discussion is simply that a same name tends to multiple forms. All the three classes above inherited the bowlingMethod() but their implementation is totally different from one another.

Types of Polymorphism
1) Compile time polymorphism (Static Polymorphism or Method Overloading)
2) Run time polymorphism (Dynamic Polymorphism or Method Overriding)

Advantages of OOPS:
  • OOP offers easy to understand and a clear modular structure for programs.
  • Objects created for Object-Oriented Programs can be reused in other programs. Thus it saves significant development cost.
  • Large programs are difficult to write, but if the development and designing team follow OOPS concept then they can better design with minimum flaws.
  • It also enhances program modularity because every object exists independently.

Conclusion
Definitions in simple words,

CLASS:
Collection of objects is called class. It is a logical entity.
A class in Java is a blueprint which includes all your data and you can create as many objects as you like.

OBJECT:
An object can be defined as an instance of a class, and there can be multiple instances of an object in a program.
An object is a bundle of data and methods.

INHERITANCE:
The process by which one class acquires the properties and functionalities of another class is called inheritance.

ENCAPSULATION:
Encapsulation simply means binding methods and variables together.
It also means to hide your data in order to make it safe from any modification.

ABSTRACTION:
Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user.

POLYMORPHISM:
When one task is performed by different ways i.e. known as polymorphism.
Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means forms.

credits: Head First Java book, beginnersbook.com, guru99, javaTpoint, edureka.

Comments

Post a Comment

Popular posts from this blog

Explain public static void main in Java

What is Automation ?