What is object-oriented programming

What is object-oriented programming in Java?

As referred to by the name, objects are used as primary sources, or hints, of what is about to happen in the code. Here, we will be studying object-oriented programming in Java. Polymorphism, Data Binding, Inheritance, etc. are some concepts done by a paradigm of Object Oriented Programming. The use of OOP is to bind the data together and the functions that work with them, preventing anyone else in the code from accessing the data saved for that function.

What is object-oriented programming?

When programming in an object-oriented (OOP) fashion, classes of objects are discovered that are closely related to the methods (functions) they are connected to. The ideas of attribute and method inheritance are also covered. 

Simula is regarded as the original object-oriented programming language. The term “fully object-oriented programming language” refers to the programming paradigm where everything is represented as an object.

Smalltalk is regarded as the first programming language that is genuinely object-oriented.

Languages that support objects include Java, C#, PHP, Python, and C++.

Implementing real-world elements, such as objects, classes, abstraction, inheritance, polymorphism, etc., is the primary goal of object-oriented programming.

Also read, Why Java is so popular among Developers!

Important OOPS concepts are

Classes

Class is a grouping of items. It makes sense as a whole. A class is similar to the template which gives a basic design and ideology of an object that can be built. Class doesn’t take up any room. A class is the object’s design manual. We must declare the class before we can construct an object.

The class can be compared to a rough draught (prototype) of a home.

Syntax

class HelloWorld {
//your code here
}

Example

class FirstProgram {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Also read, Learn about Java Datatypes and how we use them

Object

As the name defines it is an actual life entity, An object, such as a chair, bike, marker, pen, table, or car, is a thing with state and activity. The financial system is an example of an intangible item. 

An item has the following three qualities:

State: A representation of an object’s data (value).

Behavior: illustrates how something behaves or works, such as when money is deposited or withdrawn.

Identity: Usually, an object’s identity is represented by a special ID. The external user cannot see the value of the ID. However, the JVM uses it internally to uniquely identify each object.

For example, the color is black, the name is Klaus, etc. A class’s instances are objects. A class can be used as a template or model for creating new objects. 

Definitions of Objects

  • A thing that exists in the real universe is considered an object.
  • An entity at runtime is an object.
  • An entity with state and behavior is an object.
  • The object is a class instance.

Syntax

class HelloWorld {
//your code here
}
(“HelloWorld”, here is considered as an object.)

Example

class FirstProgram {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Also read, How to Search Files Effectively in the Linux Terminal

Class Methods

From the Java Method chapter, you know that methods are delivered inside a class and various actions are performed. Class methods are invoked on a class rather than a particular instance of an object. Uniform implementation across all instances of the class is ensured via the static modifier.

Numerous standard Java built-in classes, such as Math, have static methods often used in Java programs, such as Math.abs(int value).

Syntax

public class className {
   modifier static dataType methodName (inputParameters) { //static method
         //block of code to be executed
    }
}

Example

public class Main {
  static void myMethod() {
    System.out.println("Hello World!");
    }
}

The above example defines the method name, the data type of the returned value from calling the method, and the access modifier.

method Parameters hold the data that is stored in variables and used by the procedure. An input parameter’s data type and name as they appear in the method are specified in the specification of an input parameter, which is (dataType parameterName). A comma can be used to separate multiple arguments.

No instantiation is required to call static methods. This means that while other members of the class are object members, static methods can only access other static members of the class (and naturally, global and passed-in variables).

Also read, Understanding Java String methods with examples

Four Main Object-Oriented Programming Concepts of Java

The foundation of Java is object-oriented programming, or OOPS for short. Although Java is an object-oriented language, it is not just one. Java structures an application around a variety of objects and clearly defined interfaces. The following is a list of the four pillars that make up OOPS. The purpose of these ideas is to include actual entities in programs.

  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism

Abstraction

Abstraction is the process of shielding the user from implementation specifics and only exposing the functionality. We deal with ideas, not occurrences, in abstraction. As a result, the user will only be aware of “what it does,” not “how it does.”

Abstraction can be achieved in two ways:

  • Abstraction Class (0% to 100%)
  • Interface (100%)

Real-life example: If a customer buys a new vehicle he will only check about the features of the vehicle but not on the mechanism of how it works 

Regarding this OOPS pillar, it’s important to keep in mind the following:

  • If a class has one or more abstract methods, the class should be abstract.
  • Constructors, concrete, static, and final methods can all be found in abstract classes.
  • The new operator cannot be used to explicitly instantiate an abstract class. As the pre-tag below illustrates, it is feasible:

B() = new A b;

  • All of the parent class’s abstract methods must be overridden by the child class, or the child class must be declared with the abstract keyword.

Example

// Abstract class
abstract class Animal {
   public abstract void animalSound();
  // Regular method
  public void sleep() {
    System.out.println("Zzz");
  }
}

// Subclass (inherit from Animal)
class Pig extends Animal {
  public void animalSound() {
    // here, body of animalSound() is written
    System.out.println("The pig says: wee wee");
  }
}

class Main {
  public static void main(String[] args) {
    Pig myPig = new Pig();
    myPig.animalSound();
    myPig.sleep();
  }
}

Also read, Understanding Java Math Class And its different methods

Encapsulation

The process of wrapping the data and code into a single use is known as encapsulation. Real-life example: You have seen a capsule medicine where various drugs/medicines are mixed and packed inside it.

To provide encapsulation in java certain steps are followed in java such as:

  • The variables are declared private.
  • To access and update private variables or attributes, the public get and set methods are provided.

Encapsulation in Java has the following benefits:

Data Control: We can write the logic in the setter method to prevent the storage of negative integer values. Thus, we can govern the data in this manner.

Data concealment: Because the data members are private, other classes cannot access them.

Simple to test: For encapsulated classes, unit testing is simple.

Example

public class Main {
  public static void main(String[] args) {
    Person myObj = new Person();
    myObj.setName("John");
    System.out.println(myObj.getName());
  }
}

Inheritance

In Java, inheritance is the process by which one class gains access to another class’s properties and methods. When there is an is-a relationship between two objects, inheritance is applied.

Real-life example: One class in Java can access the attributes and functions of another class through a process known as inheritance. Inheritance is used when there is an is-a relationship between two things. In Java, inheritance is implemented via the extends keyword.

Before offering the code, let’s first explore how inheritance is used in Java applications using a general example. So think about an example of extending the Exception class to produce a class customized to an application that contains additional information like error codes. NullPointerException is one illustration.

In Java, there are five distinct types of inheritance:

Single Inheritance: Using the extends keyword, Class B only inherits from Class B.

Multilevel Inheritance: Using the extends keyword, class C inherits from class B, and class B inherits from class A.

Hierarchy Inheritance: Using the extends keyword, class B and class c inherit class A in the hierarchy.

Multiple Inheritance: Class C inherits both Classes A and B due to multiple inheritances. In this case, C has just one child class while A and B are both superclasses. Java does not enable multiple inheritances, however, interfaces can be used to implement it.

Hybrid Inheritance: Class D inherits both classes B and C through hybrid inheritance. Both classes B and C inherit A. Again, Class D inherits from two superclasses in this case, hence Java does not support hybrid inheritance either.

Example

class Vehicle {
  protected String brand = "Ford";
  public void honk() {
    System.out.println("Tuut, tuut!");
  }
}

class Car extends Vehicle {
  private String modelName = "Mustang";
  public static void main(String[] args) {
    Car myFastCar = new Car();
    myFastCar.honk();
    System.out.println(myFastCar.brand + " " + myFastCar.modelName);
  }
}

Also read, Things you don’t know about the Java Switch statement

Polymorphism in Java

Polymorphism is the capacity to carry out many tasks in various ways. The Greek terms poly and morphs are the sources of the word polymorphism. Poly means several, and morphs are short for forms. Polymorphism entails a diversity of forms. Polymorphism is a possibility even in cases of inheritance. Depending on the actual implementation, the functions have varying behaviors.

Real-life example

Items are delivered to the user by a delivery person. The letters will be delivered if it’s the postman. The food will be delivered to the user if it’s a food delivery boy. Similarly to this, polymorphism was used in many ways for the delivery function.

Following are the two varieties of polymorphism:

  • Compile-time versus static Polymorphism
  • Run-time or dynamic Polymorphism

Compile-time or static polymorphism is the word for polymorphism that occurs when the compiler can identify the actual function. In Java, method overloading can be used to implement compile-time polymorphism. Method overloading is the practice of having multiple functions in a class with the same name but differing signatures. The name and method arguments are contained in the method signature. Thus, various arguments are used in overloaded methods. The number of arguments or the type of arguments may vary between the arguments.

class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

class Main {
  public static void main(String[] args) {
    Animal myAnimal = new Animal();
    Animal myPig = new Pig();
    Animal myDog = new Dog();
        
    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
  }
}

Also read, A simple explanation of Java Methods/functions

Final Words

Programming in the object-oriented (OOP) manner identifies classes of objects that are closely related to the methods (functions) with which they are associated. It also covers the concepts of attribute and method inheritance. It is a method for storing data along with the operations required to process that data that is based on the mathematical field known as “abstract data types.” Programming could advance to a more abstract level thanks to OOPs. Above was a discussion about the OOPs programming in Java, we will be learning more about Java in our next class.