top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Java OOPs Concepts

Introduction

Java OOPs concepts are a programming paradigm based on classes, objects, and inheritance. They are used to create reusable and maintainable codes. It helps break down problems into smaller parts so developers can build, modify, and extend easy applications. This article thoroughly covers the different OOPs concepts in Java with examples.

Overview

This article deals with the different aspects of OOP in Java, such as access modifiers, message passing, and different pillars of OOPs concepts in Java. This article also touches upon OOPs concepts with examples of code and their explanations.

Access modifier

In Java, an access modifier is a keyword that determines the accessibility or scope of a class, variable, method, or constructor. There are four access modifiers in Java:

Private: 

Private members are only accessible within the same class.

class Data {
       private String name;
}
public class Main {
    public static void main(String[] main){
        Data d = new Data();       
        d.name = "zozozo";
    }
}

Default (no modifier): 

Members with no access modifier are accessible within the same package.

package defaultPackage;
class Logger {
void message(){
System.out.println("run this message"); 
} }

This code does not have any executable statements. Therefore, a “main” method should be added to a separate class in order to run this code.

Protected

Members with protected access modifiers are accessible within the same package and in subclasses outside the package.

class Bird {
    protected void display() {
        System.out.println("I am a Bird");
    }
}
class Parrot extends Bird {
    public static void main(String[] args) {
        Parrot parrot = new Parrot();
        parrot.display();
    }
}

Public

Members with public access modifiers are accessible from anywhere in the application.

MyClass.java file:

public class MyClass {
    public void display() {
        System.out.println("This is an example of a public access modifier.");
    }
}

Main.java file:

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.display();
    }
}

Note that to run this code, you must save it in a file named MyClass.java and another file named Main.java in the same directory.

Then, you need to compile both files together by running the following command in the terminal:

javac MyClass.java Main.java

This will generate two .class files: MyClass.class and Main.class.

Finally, run the program by executing the following command:

java Main

By using access modifiers, we can control the visibility and access of class members and encapsulate them properly to achieve data hiding and abstraction.

Message passing

Message passing is a way of exchanging information between different parts of a program in Java. In message passing, objects interact by sending and receiving messages. 

Message passing is a tool in Java for object-oriented programming. In this, objects in Java communicate with each other by sending and receiving messages. A message typically contains a method invocation. Other parameters are also present that are needed to perform the operation.

Method invocation means a method of an object called to perform an operation. Overall, message passing is a crucial concept in Java programming. In essence, it allows objects to communicate with each other and perform complex tasks.

Here is an example of code showing message passing in Java:

import java.util.Observable;
import java.util.Observer;
class MessageSender extends Observable {
    public void sendMessage(String message) {
        setChanged();
        notifyObservers(message);
    }
}
class MessageReceiver implements Observer {
    @Override
    public void update(Observable observable, Object arg) {
        if (observable instanceof MessageSender) {
            System.out.println("Received message: " + arg);
        }
    }
}
public class Main {
    public static void main(String[] args) {
        MessageSender sender = new MessageSender();
        MessageReceiver receiver = new MessageReceiver();
        sender.addObserver(receiver);
        sender.sendMessage("Hello, world!");
    }
}

In this example, the “MessageSender” object is an observable object. The “MessageReceiver” object is an observer object. The “MessageSender” object has a method “sendMessage()”. This sends a message to its observers. When a message is sent, the “setChanged()” method is called to mark the observable object as changed. Also, the “notifyObservers()” method is called to notify all its observers. The “MessageReceiver” object has an “update()” method that gets called when it receives a message from its observable object. The “update()” method prints the received message to the console in this example.

OOPS concepts are as follows: 

Class

In Java, a class is a blueprint or a template for creating objects. It defines the attributes and behaviors of objects of a specific type. The fields of the objects show the attributes of a class. The methods of the objects show the behaviors of a class.

Here is an example of a simple class in Java:

public class Person {
    private String name;
    private int age; 
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

In this example, the “Person” class has two private fields, “name” and “age.” The “Person” class also has four public methods: “getName(),” “getAge(),” “setName(),” and “setAge().” It also has a constructor that takes in a name and an age and sets the corresponding fields.

With this class, we can create objects of the type “Person.” We can set their attributes using the “setName()” and “setAge()” methods. We can also get their attributes using the “getName()” and “getAge()” methods.

We must first add a “main” method to the “person” class with this argument:

“public static void main(String[] args) {“

Then, we can add the following code:

Person person1 = new Person("John", 25);
System.out.println("Name: " + person1.getName() + ", Age: " + person1.getAge());
Person person2 = new Person("Jane", 30);
System.out.println("Name: " + person2.getName() + ", Age: " + person2.getAge());

Object

In Java, an object is an instance of a class. It is a basic unit of object-oriented programming. It contains both data and behavior in the form of variables and methods.

To create an object, you first need to define a class. Once you have defined a class, you can create objects of that class using the new keyword, followed by the name of the class and a set of parentheses.

For instance, if you have defined a “Person” class with properties such as “name”, “age”, and “address”, as well as methods such as “getName()” and “getAge()”. To create an object of this class, you could use the following code:

Person person = new Person("John", 25);

This creates a new “Person” object with the name "John" and the age “25”. It also assigns it to the “person” variable. You can then access the properties and methods of the object using the dot notation like this:

String name = person.getName();
int age = person.getAge();

This retrieves the name and age of the “person” object. Then it stores them in the “name” and “age” variables, respectively.

Method and method passing

In Java, a method is a set of instructions that perform a given task. Methods allow us to organize our code and make it reusable. In Java, a method can be defined inside a class and have a return type, parameters, and access modifiers.

If we want to pass arguments to a method, we must specify the data type and name of the arguments in the method definition. When we call the method, we pass in the actual values we want to use as arguments.

Here is an example:

public class Calculator {
    public int add(int x, int y) {
        return x + y;
    }
    public static void main(String[] args) {
        Calculator calc = new Calculator();       
        int sum = calc.add(2, 3);
        System.out.println("Sum is: " + sum);
    }
}

You need to open a text editor to run this code. Then, you need to copy the code into a new file. There, you need to save the file with a “.java” extension: “Calculator.java”. Then, you need to open a terminal and navigate to the directory where you saved the file. Then, compile the code using the “javac” command: “javac Calculator.java”. Finally, run the compiled code using the “java” command: “java Calculator”. This will execute the main method of the Calculator class.

Pillars of OOPs

The Pillar of OOPs can also be called the features of OOPs in Java. Some key features are Abstraction, Encapsulation, Inheritance, Polymorphism, Class, and Object.

Abstraction

Abstraction is the process of hiding the implementation details in Java and showing only the functionality to the user. It helps to reduce the complexity of the processes and increase efficiency.

abstract class Shape {
   abstract void draw();
}
class Circle extends Shape {
   void draw() {
      System.out.println("Circle drawn");
   }
}
class Rectangle extends Shape {
   void draw() {
      System.out.println("Rectangle drawn");
   }
}
public class Main {
   public static void main(String[] args) {
      Shape shape = new Circle();
      shape.draw();
      shape = new Rectangle();
      shape.draw();
   }
}

Encapsulation

Encapsulation is the mechanism of binding data members and member functions in a single unit called a class. It helps to hide the data from other classes and restrict access.

Student.java file:

public class Student {
   private String name;
   private int rollNo;
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getRollNo() {
      return rollNo;
   }
   public void setRollNo(int rollNo) {
      this.rollNo = rollNo;
   }
}

Main.java file:

public class Main {
   public static void main(String[] args) {
      Student student = new Student();
      student.setName("John");
      student.setRollNo(1);
      System.out.println("Name: " + student.getName() + ", Roll No: " + student.getRollNo());
   }
}

Inheritance 

In Java, inheritance is the process of creating a new class by inheriting properties and behavior from an existing class. It helps to reuse the code and reduce redundancy.

Here is a code explaining Inheritance: 

class Animal {
   void eat() {
      System.out.println("Animal is eating");
   }
}
class Dog extends Animal {
   void bark() {
      System.out.println("Dog is barking");
   }
}
public class Main {
   public static void main(String[] args) {
      Dog dog = new Dog();
      dog.eat();
      dog.bark();
   }
}

Polymorphism 

Polymorphism is the ability of an object to take on many forms in Java. It is implemented using method overloading and method overriding.

class Animal {
    public void makeSound() {
        System.out.println("Animal is making a sound");
    }
}
class Dog extends Animal {
    public void makeSound() {
        System.out.println("Dog is barking");
    }
}
class Cat extends Animal {
    public void makeSound() {
        System.out.println("Cat is meowing");
    }
}
public class Main {
    public static void main(String[] args) {
        Animal animal1 = new Dog();
        Animal animal2 = new Cat(); 
        animal1.makeSound(); 
        animal2.makeSound();
    }
}

Compile-time polymorphism

Compile-time polymorphism is a feature in Java where a class has multiple methods with the same name but different parameters or argument types. The correct method to execute is determined at compile-time based on the method signature.

Here is an example code that demonstrates compile-time polymorphism:

Calculator.java file:

public class Calculator {
    public int add(int x, int y) {
        return x + y;
    }
    public double add(double x, double y) {
        return x + y;
    }
}

Main.java file:

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        int sum1 = calc.add(2, 3);
        System.out.println("Sum of integers: " + sum1);
        double sum2 = calc.add(2.5, 3.5);
        System.out.println("Sum of doubles: " + sum2);
    }
}

To run this code, save it with a .java extension: “Main.java.” Then compile it using the command “javac Main.java”. Then, run the compiled code using the command “java Main.” Note that both “Calculator.java” and “Main.java” files will be saved in the same directory.

Runtime polymorphism

Runtime polymorphism is a process in Java to determine which method of a class is to be executed at runtime. This is based on the specified object.

Here is an example code that demonstrates runtime polymorphism:

class Animal 
    public void makeSound() {
        System.out.println("Animal is making a sound");
    }
}
class lion extends Animal {
    public void makeSound() {
        System.out.println("lion is roaring");
    }
}
class Cat extends Animal {
    public void makeSound() {
        System.out.println("Cat is meowing");
    }
}
public class Main {
    public static void main(String[] args) {
        Animal animal1 = new lion();
        Animal animal2 = new Cat();
        animal1.makeSound(); 
        animal2.makeSound();
    }
}

Conclusion 

Java OOPs concepts help programmers develop robust applications. They enable developers to create complicated programs by dividing problems into smaller, more manageable components and modeling them as objects. 

The Java OOPs concepts are moderately complex but can be mastered with proper guidance and training. Online learning platforms like upGrad can assist you in mastering these concepts easily.

FAQs

1. What is OOP in Java?

OOP in Java stands for “Object-Oriented Programming.” The programming paradigm emphasizes using objects to represent data and behaviors.

2. What is the final method in Java?

A final method is a method that a subclass in Java cannot override. 

3.  What is a static block in Java?

A static block is a code block executed when a class is loaded in Java. It is typically used for static initialization.

Leave a Reply

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