Object Oriented Programming In Java

Introduction

In this article, we will learn about Object-Oriented Programming in Java with its different concepts like Class, Object, Inheritance, Abstraction, Encapsulation, and Polymorphism with example programs.

Java

Java technology is both a programming language and a platform. It is a high-level, class-based, and object-oriented programming language. Java is a secure and powerful language. Java runs on multiple platforms. It means that it can work on any software or hardware platform. It has a virtual machine specification. It has its own runtime environment JRE (Java Runtime Environment) and an API (Application Programming Interface) Specification. The Java programming language is a high-level language.

The following types of applications are developed in Java.

  • Standalone Application
  • Web Application
  • Enterprise Application
  • Mobile Application

To learn more about how to program in Java, Click Java Basics.

Object-Oriented Programming

Java is an object-oriented programming language. It means that all things are objects in Java and in other words, we can say that Java is a collection of objects.

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

Object Oriented Programming

Advantages of Object-Oriented

The following are the advantages of the Oops in Java:

  • It makes the development procedure easy.
  • Oops provides an efficient way to interact with real-world data.
  • Real-world problems can be solved easily by the Oops concept.
  • Data hiding is the main advantage of the Oops concept.
  • Data can be shared anywhere in the project through the Oops concepts.

Class in Java

Java class is the basic building block of the Java programming language. Java class is a template that is used to create objects and to define data types and methods. Java class objects should have basic class properties. Java class is the basic concept of object-oriented programming languages. Java class is a user-defined template or blueprint where objects, data members, and methods are defined with a set of instructions to build a specific type of object. The variables and methods of the same Java class are common for all the objects of the class. In Java, the class keyword is used to define a Java class.

How is a Java Class defined?

Syntax

class <class-name>
{
    [data members];
    [methods];
}

The code example of the Java class is listed below.

public class ClassExample {  
  
    //Data Members  
    int x = 5;  
    int y = 10;  
  
    void method() {  
        System.out.println("This is method");  
    }  
  
    public static void main(String args[]) {  
  
        ClassExample obj = new ClassExample();  
  
        int c = obj.x + obj.y;  
        System.out.println(c);  
  
        obj.method();  
    }  
} 

Explanation of the Program

class ClassExample{

the class keyword is used to declare a class in Java such as ClassExample is a class name.

Data Members

  • int x = 5;
  • int y = 10;

We create two integer-type variables named x and y. void method()

We create a method of the void type named method().

Public static void main(String args[]){

Public is an access modifier and is publically accessible everywhere which means it’s visible to all.

static

Static is a keyword. When we use a static keyword with any method, it is called a static method. It is used basically in memory management and there is no need to create an object to call it a static method.

void

Void is a return type and it’s not returning any value to a method. main

The Main is used to start a program. Without the main, you cannot run your program.

String [] args

String [] args is used for a command-line argument. int c= obj.x + obj.y;

In this line, we create a variable c, store the addition of x and y in that variable, and print the c in the next line "System.out.println(c);

obj. method()

Here we call the method of the class by the object of the class. The above program generates the following output.

Class Output Image1

Objects in Java

An object is a basic concept of oops like Java classes. objects like an entity, which has a state and behavior like a car, mobile, pencil, cat, etc. A car has states (its color, name, and brand) and behavior (running). Objects are an instance of a java class and objects can be tangible and intangible. Objects represent identity, which uniquely identifies it. One car's number plate is a different number from other cars. So, it is the car's identity that is unique. Objects represent the value of an object like car name, color, and brand. Objects represent the functionality of an object like a car's functionality is running.

How do you create an object in the Java class?

In Java, a new keyword is used to create an object. Syntax

<class-name> [object-name] = new <class-default-conetructor>

The complete example program of Object is listed below.

public class ObjectExample {  
    public static void main(String args[]) {  
  
        ObjectExample obj = new ObjectExample();  
  
        System.out.println(obj.getClass());  
    }  
} 

Explanation

In the above code example first, we create a new Java class named "ObjectExample".

  • ObjectExample obj= new ObjectExample();: This line is used to create the object of the class.
  • obj.getClass(): obj is the object name of the class and the getclass() method is used to get the name of the class.

The above code generates the following output.

ObjectClass Output

Inheritance in Java

In Java, Inheritance is a process, where one class object acquires all the properties and behaviors of the parent class object. It represents the IS-A relationship, also called a parent-child relationship. With the use of an inheritance, we can manage the information easily.

In an inheritance, we can create new classes, which are built upon the existing classes. The main benefit of inheritance is we can reuse the methods and variables of the parent class, and add new methods and variables also. The class, which acquires the properties of the parent class is called a subclass (derived class, child class) and the class, whose properties are acquired is called a superclass (base class, parent class).

Parent class in Java Inheritance

The class inherited by the other classes is called the Parent class, Superclass, and base class.

Child class in Java Inheritance

The class which inherits the parent class is called the child class, subclass, and derived class.

Advantages of Inheritance in Java

  • Code reusability: Code Reusability is the main advantage of inheritance in Java because we can extend the classes, so the code of the parent class can be used in the child classes that inherit that parent class.
  • Method overriding: In the Method Overriding concept of inheritance in Java, the parent class and child class have the method with the same name and same return type.

Syntax of Inheritance

class Subclass-name extends Superclass-name
{
    //variables and methods;
} 

Note

In Java, the “extends” keyword is used to inherit the properties of a class.

The complete program example of inheritance in Java is listed below.

public class Vehicle {  

    int carSpeed = 90;  
} 

Explanation

First, we create a parent class named Vehicle, In this class, we create an integer type variable named "carSpeed=90".

public class Car extends Vehicle {  
    int speed= 60;  
  
    public static void main(String args[]){  
        Car c = new Car();  
        System.out.println("Vehicle Speed : " +c.speed);  
        System.out.println("Vehicle Speed : " +c.carSpeed);  
    }  
} 

Explanation

Here we create a child class named Car and extend the Vehicle class, we create an integer type variable named speed=60. We create the object of the car class. Now we use the object of the car class to access the variables of the parent class and the child class.

The above program generates the following output.

Inheritance Example

Types of Inheritance in Java

In Java, there are various types of inheritance which are shown below

1. Single inheritance in Java

Single Inheritance Image

2. Multilevel Inheritance in Java

Multilevel Inheritance Image

3. Hierarchical Inheritance in Java

Hierarical Inheritance Image

4. Multiple Inheritance in Java

Multiple Inheritance Image

5. Hybrid Inheritance in Java

Hybrid Inheritance Image

On the basis of class, three types of inheritance in Java exist, which are single, multilevel, and hierarchical.

In Java, multiple and hybrid inheritance are not supported through the class. Both are supported through the interface only.

Why is Multiple inheritance not supported in Java?

Java is a very powerful and simple language. Multiple inheritance increases the complexity of a program. To reduce the difficulty and make language simple, Java does not support multiple inheritance.

Suppose, we have three classes X, Y, and Z. Z is a child class and inherits the properties of class X and class Y. X and Y both are parent classes. If X and Y classes have the same method and when we want to call that method from the child class object, it gives an error since there will be an ambiguity (confusion) to call method X or Y class. Due to this, Java does not support multiple inheritance through classes.

Polymorphism in Java

Polymorphism has many forms. Polymorphism is the capability of an object to take on many forms. In Polymorphism, we can do a single task in different ways.

Java mainly uses polymorphism in OOPS, which occurs when a parent class reference is used to refer to a child class object.

In Java, there are two types of polymorphism, which are-

  • Compile-time polymorphism
  • Runtime polymorphism

We can do polymorphism by method overloading and method overriding.

Compile-time polymorphism in Java

When we overload the static method in Java, it is called a compile-time polymorphism. In other words, we can say, that a class has more than one method with the same name but different arguments.

The complete program example of compile-time polymorphism in Java is listed below.

public class PolymorphismExample1 {  
    void add(int x, int y) {  
        System.out.println(x + y);  
    }  
  
    void add(int x, int y, int z) {  
        System.out.println(x + y + z);  
    }  
  
    public static void main(String args[]) {  
        PolymorphismExample1 obj = new PolymorphismExample1();  
        obj.add(10, 20, 30);  
        obj.add(30, 20);  
    }  
  
} 

Explanation

In the example, shown above, we create an add () method and overload that method with a different argument. It is an example of compile-time polymorphism.

The above program generates the following output.

Polymorphism Example1

Run time Polymorphism in Java

In Java, runtime polymorphism is a process in which we call an overridden method, which is resolved at runtime. It is also called a dynamic method dispatch. In runtime polymorphism, an overridden method is called through the reference variable of a parent class.

The complete program example of Run time Polymorphism in Java is listed below.

class RunTimePolymorphismexam1 {  
  
    void work() {  
        System.out.println("working");  
    }  
} 
public class RunTimePolymorphismexam2 extends RunTimePolymorphismexam1 {  
    void work() {  
        System.out.println("working hard");  
    }  
  
    public static void main(String args[]) {  
        RunTimePolymorphismexam1 e = new RunTimePolymorphismexam2();//upcasting  
        e.work();  
    }  
} 

Explanation

In the example, shown above, first, we create two classes, RunTimePolymorphismexam1, and RunTimePolymorphismexam2. The programmer class inherits the RunTimePolymorphismexam1 class and overrides the work () method of the parent class. We call the work method by the reference variable of the parent class and it refers to the child class object. Hence, the child class method is invoked at the runtime by JVM.

The above program example generates the following output.

Run Time Polymorphism example

Abstraction in Java

In Java, abstraction is a procedure to hide the implementation details from the user and provides only functionality to the user.

In other words, it hides all the internal details and provides only important things to the user. For example in the calculator, when we want to calculate some data, we use its keys but we don’t know, how it works internally. It provides only important things to the user and hides the internal process from the user.

In Java, there are two ways to achieve abstraction, which are-

  • Abstract class
  • Interface

Abstract class in Java

In Java, when we use abstract keywords with any class, this class is called an abstract class.

  • An abstract class can have abstract methods and non-abstract methods.
  • If a class has an abstract method, this class must be an abstract class.
  • If we want to use an abstract class, it needs to be extended and its method implemented.
  • If we extend an abstract class, we have to provide an implementation for all the abstract methods in it.
  • We can’t instantiate an abstract class.

The complete example program of the Abstract class is listed below.

abstract class Person {  
    abstract void work();  
} 
public class Girl extends Person {  
  
    @Override  
    void work() {  
        System.out.println("Working Hard");  
    }  
  
    public static void main(String args[]) {  
        Person obj = new Girl();  
  
        obj.work();  
    }  
} 

Explanation

In this example, we create a person class, which contains one abstract method work and its implementation is provided by the women class.

The above program generates the following output.

Abstract class example

Abstract method in Java

In Java, when we use an abstract keyword with any method, the method is called an abstract method and an abstract method contains a method signature, but no method body.

The complete program example of an abstract method is listed below.

abstract class AbstractMethod1 {  
    abstract void call();  
} 
class AbstractMethod2 extends AbstractMethod1 {  
  
    //implementation is provided by others i.e. unknown by end user  
    void call() {  
        System.out.println("Abstract Method implementation");  
    }  
} 
class AbstractMethod3 extends AbstractMethod2 {  
  
    void call() {  
        System.out.println("Abstract Method");  
    }  
  
} 
public class AbstratUserClass {  
      
    // method is called by programmer or user  
      
    public static void main(String args[]) {  
          
        AbstractMethod1 m = new AbstractMethod3();//object is provided through method  
        m.call();  
          
    }  
} 

Explanation

In this example, AbstractMethod1 class is an abstract class and its implementation is provided by AbstractMethod2 and AbstractMethod3 classes. In it, if we create an instance of the AbstractMethod2 class, the call () method of the AbstractMethod2 class will be invoked similarly to the AbstractMethod3 class. In reality, we don’t know about the implementation class i.e. hidden to the user, and the object of the implementation class is provided by the factory method. An abstract class can have variables, an abstract method, a method body, a constructor, and a main () method.

The above program generates the following output.

Abstract Method Example

Encapsulation in Java

In Java, encapsulation is a concept of OOPS. It is a procedure of wrapping the code and data together into a single unit, for example, tea is a mixture of several items. Encapsulation is a process of binding related methods and variables in a protective wrapper (Class) with necessary access modifiers. With the use of encapsulation, the code can be secured from unauthorized access by others and is easy to maintain.

We can create a fully encapsulated class by creating all the data members of the class as private. Java provides setter and getter methods to set and get the data in it. An example of a fully encapsulated class is a Java bean class.

Advantages of Encapsulation

  • It provides control over the data. We can write the logic inside the setter method.
  • We can make our class read-only or write-only with the use of the setter and getter method.
  • It makes the code more secure, flexible, and maintainable.
  • In encapsulation, we can change one part of the code easily without affecting the other part of the code.

The complete program example of Encapsulation is listed below.

package EncapsulationExample;  
  
public class EncapsulationExample1 {  
    private String name;  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
} 
package EncapsulationExample;  
  
public class EncapSulationExampleUSer {  
  
    public static void main(String[] args) {  
  
        EncapsulationExample1 b = new EncapsulationExample1();  
  
        b.setName("C#Corner");  
        System.out.println(b.getName());  
  
    }  
  
} 

Explanation

In the example of the encapsulation program, First, we create a package named EncapsulationExample. In this package, we create two Java classes EncapsulationExample1 and EncapsulationExampleUser. The example program shown above has only one data member with its setter and getter methods.

The above program generates the following output.

Encapsulation Example Output

Summary

In this article, we will learn about Object-Oriented programming concepts in Java. We learn about Object, class, Inheritance, Polymorphism, Encapsulation, and Abstraction with example programs.