Java

OOPs Concepts In Java

You will discover Java’s OOPs concepts in this manual. The idea of “objects” is the foundation of object-oriented programming system (OOPs), a type of programming. The improvement of programs’ readability, flexibility, and maintainability is the main goal of object-oriented programming.

Data and the behavior it exhibits are combined into a single unit called an object in object-oriented programming. It simplifies the programming’s understanding. To ensure that you have no trouble comprehending OOPs in Java, we will go over all the OOPs aspects in depth, including inheritance, polymorphism, abstraction, and encapsulation.

Object-oriented programming is supported by a number of popular programming languages, including Java, C++, Python, C#, Perl, JavaScript, Ruby, Smalltalk, etc.

What is OOPs Concepts in Java

The following object-oriented programming ideas are included in OOPs:

  • Object
  • Class
  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism

1. Object

A representation of an item can be thought of as an entity with state and behavior. A car, for instance, is an example of an object with states like color, model, price, and behavior like speed, start, gear change, stop, etc.

Let’s examine how state and behavior differ from one another. The state of an object is a piece of data that may be expressed as a value, similar to how a car’s price or color are variables in programming. The behavior is a collection of activities that when taken collectively may accomplish a goal, much like a method of a class. For instance, shifting into a different gear is a behavior since it requires moving the gear handle as well as controlling the speed and clutch.
Let’s look at a couple more objects as examples:

Examples of states and behaviours
Example 1:
Class: House
State: address, color, area
Behaviour: Open door, close door

Let’s look at how these states and behaviors may be written in a Java application. States and behaviors may both be modeled using instance variables and class methods, respectively.

class House {
   String address;
   String color;
   double area;
   void openDoor() {
      //Write code here
   }
   void closeDoor() {
      //Write code here
   }
 ...
 ...
}

Example 2:
Class: Car
State: color, brand, weight, model
Behaviour: Break,  Accelerate,  Slow Down,  Gear change.

Note: As we have seen in the above example, the states and behaviours of an object can be represented by variables and methods in the class.

2. Class

You may think of a class as a blueprint that you can use to build as many different types of objects as you desire. Here, for instance, we have a class called Website with two data members. Although this is only a blueprint and doesn’t represent any particular website, we can use it to construct Website objects that do. When building the two objects, we used constructors to give each one of them unique characteristics.

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", 11);
      Website obj2 = new Website("google", 28);

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

Output:

beginnersbook 11
google 28

3. Abstraction

With abstraction, you “hide” unneeded information from the user and only display “relevant” information. For instance, when you connect into your bank account online, what occurs after you push login, how the input data is delivered to the server, and how it is confirmed, are all abstracted away from you. You may learn more about it here: Java Abstraction.

Abstract Class Example:

We have an abstract class here. Animals have an abstract method called animalSound(), but because each animal’s sound is unique, there is no purpose in providing the code for this method as each child class must override it and provide information on how it should be implemented. Because of this, we made it abstract.

Now that each animal must have a sound, we made it necessary for the child class to provide implementation details by making this function abstract. We can guarantee that every animal has a sound by doing this.

//abstract class
abstract class Animal{
   //abstract method
   public abstract void animalSound();
}
public class Dog extends Animal{

   public void animalSound(){
	System.out.println("Woof");
   }
   public static void main(String args[]){
	Animal obj = new Dog();
	obj.animalSound();
   }
}

Output:

Woof

4. Encapsulation

Encapsulation is the simple act of coupling an object’s state (fields) and behavior (methods). Encapsulation is done when you create a class.

Example

  1. Make the instance variables private so that no one outside the class may access them directly. Only the class’s methods may be used to set and get the values of these variables.
  2. In the class, there should be getter and setter methods for setting and retrieving the values of the fields.
class EmployeeCount
{
   private int numOfEmployees = 0;
   public void setNoOfEmployees (int count)
   {
       numOfEmployees = count;
   }
   public double getNoOfEmployees () 
   {
       return numOfEmployees;
   }
}
public class EncapsulationExample
{
   public static void main(String args[])
   {
      EmployeeCount obj = new EmployeeCount ();
      obj.setNoOfEmployees(5613);
      System.out.println("No Of Employees: "+(int)obj.getNoOfEmployees());
    }
}

Output:

No Of Employees: 5613

The class EncapsulationExample won’t be able to retrieve the NoOfEmployees directly if it uses the Object of type EmployeeCount. To set and get the value, it must utilize the setter and getter methods of the same class.

What advantages does encapsulation provide in Java programming?
Well, if you wish to modify the implementation details of the class EmployeeCount at some point in the future, you are free to do so without impacting the classes that use it.

5. Inheritance

Inheritance is the process through which a class acquires the traits and capabilities of another class. Each subclass specifies just those characteristics that are exclusive to it; the other features may be inherited from the parent class, which promotes the notion of code reuse.

  1. The act of creating a new class based on an existing class by expanding its shared data members and functions is known as inheritance.
  2. The ability to reuse code thanks to inheritance makes your Java program more reusable.
  3. The base class or super class is the name given to the parent class. The term “derived class,” “subclass,” or “child class” refers to the child class that extends the base class.

The primary benefit of inheritance is that the base class’s code does not have to be duplicated in the child class.
The child class may also utilize the base class’s variables and methods.

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
{
}

Generalization and Specialization:

One must first determine the similarities between various classes in order to create the base class before one can apply the notion of inheritance in an OOP.

Generalization is the process of determining the commonalities between several groups. Extraction of common traits from two or more classes and fusion of those traits into a generalized superclass is the process of generalization. Attributes or techniques might be shared traits.

Specialization is the process of deriving additional subclasses from an existing class as opposed to generalization. A subclass may be established if it turns out that certain characteristics or methods only apply to part of the class’s objects.

Inheritance Example

We have a parent class teacher and a kid class math teacher in this scenario. The code that is already present in the current class may be used in the MathTeacher class without having to write it again. Since the college name, designation, and does() function are present and shared by all instructors, MathTeacher class does not need to develop the code for them; instead, they may inherit the common data elements and methods 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

As demonstrated in the accompanying figure, multiple inheritance is not permitted in Java, although multi-level inheritance is.

Types of Inheritance:

Single Inheritance: refers to a parent-child connection between classes, where one class extends the other class.

Multilevel inheritance: refers to the connection between a class extending the child class and the parent class. Class A, for instance, extends class B, and class B, extends class C.

Hierarchical inheritance: relates to a parent-child connection between classes when more than one class extends the same class. For instance, class B and class C both extend class A.

Multiple Inheritance: refers to the idea that one class may extend several classes, i.e., a child class can have two parent classes. You may learn more about Java’s lack of support for multiple inheritance here.

6. Polymorphism

A characteristic of object-oriented programming called polymorphism enables us to carry out a single operation in several ways. For instance, if the class Animal had a method called animalSound(), we are unable to implement it since we are unsure of which Animal classes will extend the Animal class. Therefore, we abstract this procedure as follows:

public abstract class Animal{
   ...
   public abstract void animalSound();
}

Let’s say that the Animal class is extended by the Dog and Lion classes. There, we may describe the implementation.

 

public class Lion extends Animal{
...
    @Override
    public void animalSound(){
        System.out.println("Roar");
    }
}

and

public class Dog extends Animal{
...
    @Override
    public void animalSound(){
        System.out.println("Woof");
    }
}

As you can see, there were several methods to carry out the same action even though animalSound() was a standard operation for all subclasses. This is the ideal illustration of polymorphism (feature that allows us to perform a single action in different ways).

Types of Polymorphism

  1. Static Polymorphism
  2. Dynamic Polymorphism

Static Polymorphism:

Static polymorphism is a kind of polymorphism that is resolved by the compiler. Method overloading is an example of static polymorphism.

Method overloading: This enables us to have many methods in a class with the same name but different signatures.

class DisplayOverloading
{
    public void disp(char c)
    {
         System.out.println(c);
    }
    public void disp(char c, int num)  
    {
         System.out.println(c + " "+num);
    }
}
public class ExampleOverloading
{
   public static void main(String args[])
   {
       DisplayOverloading obj = new DisplayOverloading();
       obj.disp('a');
       obj.disp('a',10);
   }
}

Output:

a
a 10

Dynamic Polymorphism

Additionally called Dynamic Method Dispatch. Runtime polymorphism, often known as dynamic polymorphism, is a procedure in which a call to an overridden method is actually resolved at runtime.

Example

class Animal{
   public void animalSound(){
	System.out.println("Default Sound");
   }
}
public class Dog extends Animal{

   public void animalSound(){
	System.out.println("Woof");
   }
   public static void main(String args[]){
	Animal obj = new Dog();
	obj.animalSound();
   }
}

Output:

Woof

Given that the method animalSound is shared by the parent and child classes, The JVM decides which method will be invoked at runtime.

Few more overriding examples:

Animal obj = new Animal();
obj.animalSound();
// This would call the Animal class method

Dog obj = new Dog();
obj.animalSound();
// This would call the Dog class method

Animal obj = new Dog();
obj.animalSound();
// This would call the Dog class method

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button