How to Implement the Revolutionary OOPs Concepts in Java

There’s a reason why Java is one of the top two programming languages in the world—it has some of the most powerful and useful features available. Like OOPs concepts in Java.

OOPs concepts in Java mainly focus on providing an organized and clear structure to data members; and manipulation methods in a program in the form of an object. Unlike procedural programming, the revolutionary object-oriented programming approach improvises the programming capabilities and functionalities to an exponential level.

What Is a Class?

As we mentioned before, a class in object-oriented programming is a blueprint for storing data members and data manipulating methods combined in the form of a data structure. 

To declare a class, we use the keyword class, followed by a user-defined name.

Syntax:

<Access Modifier> class <name_of_the_class>{

 Data members;

 Data methods;

 Class Statements;

}

Example:

package Simplilearn;

import java.util.Scanner;

public class Area {

   public static void main (String[] args)

   {

    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter the length of the Rectangle:");

    double l = scanner.nextDouble();

    System.out.println("Enter the breadth of the Rectangle:");

    double b = scanner.nextDouble();

    double a = l*b;

    System.out.println("Area of the given Rectangle is:"+a);

   }

}

//Output:

Enter the length of the Rectangle:

21

Enter the breadth of the Rectangle:

34

Area of the given Rectangle is:714.0

Static Keyword

The static keyword in Java acts as an access modifier. When a particular class, method, or variable is declared using the static keyword, then those declared items. are prevented from modifications or gaining access. Their original values and properties are left unchanged.

Syntax:

<access_modifier> static <name_of_the_class>;

static <data type> <name_of_the_variable>;

static <method_name>;

Example:

package Simplilearn;

class Employee {

 int E_ID;

 String name;

 static String Organisation = "XYZ-Org";

 Employee(int e_id, String N) {

  E_ID = e_id;

  name = N;

 }

 void display() {

  System.out.println(E_ID + " " + name + " " + Organisation);

 }

}

public class Static {

 public static void main(String args[]) {

  Employee e1 = new Employee(10432, "John");

  Employee e2 = new Employee(10483, "Anthony");

  Employee e3 = new Employee(10232, "Steve");

  Employee e4 = new Employee(10856, "Thomas");

  e1.display();

  e2.display();

  e3.display();

  e4.display();

 }

}

//Output:

10432 John XYZ-Org

10483 Anthony XYZ-Org

10232 Steve XYZ-Org

10856 Thomas XYZ-Org

This Keyword

The term "this" is a keyword in Java, which is a reference variable that refers to the current object. It is used in various places based on its requirements. A few of the implementations include:

  • To invoke a method from the current class
  • To invoke a constructor from the current class
  • To refer an instance variable from the current class
  • To return the instance of the current class from a method
  • To pass the arguments to a method or constructor 

Syntax:

this.<method_name>;

this.<variable_name>;

Example:

package Simplilearn;

class StudentData {

 int ID;

 String name;

 int rank;

 StudentData(int ID, String name, int rank) {

  this.ID = ID;

  this.name = name;

  this.rank = rank;

 }

 void display() {

  System.out.println(ID + " " + name + " " + rank);

 }

}

public class This {

 public static void main(String args[]) {

  StudentData student1 = new StudentData(8010, "sam", 18);

  StudentData student2 = new StudentData(8121, "Jennifer ", 3);

  student1.display();

  student2.display();

 }

}

//Output:

8010 sam 18

8121 Jennifer 3

What Is an Object?

An object is the building block for every object-oriented programming language. An object is created when a specific class is used. An object may include properties and methods. Sometimes it may also include another object.

Syntax:

<class_name> <object_name> = new <class_name>(“<parameters”);

Example:

Employee e1 = new Employee ("Sharon", 102030, "B+");

What Is a Constructor?

A constructor is a unique method that makes use of the class as a blueprint. It initializes the class objects and constructs them.

Syntax: 

<class_name> <object_name> = new <class_name>(“<parameters”);

Example:

Student s1 = new Student (“Jayson”, 22901, “First-Grade”);

What Is a Method?

A Java method is a location where users define the operations that they’d like to apply to their data members. A programmer defines the method inside the class.

Syntax:

<Access_Modifier> <Datatype> <Method_Name> (<Parameters>) {

 Return <Result>;

}

Example:

Public float sum(float x, float y) {

 return z=x+y;

}

OOPs Concepts in Java

Object-oriented programming is a structured approach to building software. Through it, classes are the building blueprints holding the methods, and objects are the basic building blocks that store the class's instances. 

In Java, four governing laws define Object-Oriented Programming. They include:

Abstraction in Java OOPs Concepts

abstraction.

In object-oriented programming, abstraction keeps the user from viewing the implementation of the sophisticated methods. In other words, users can only see the necessary details and information that they wish to see and hide the implementation's unnecessary complexities.

In Java, the abstraction is achieved when the following special classes are incorporated:

  • Interface Class
  • Abstract Class

Interface in Java

/interface

An interface in Java acts as a container that stores only the method's signatures and exclude the data members and their method definitions. Using interfaces reduces the code complexity and improves the code’s readability.

Syntax:

<Acees_Modifier> interface <Interface_Name> {

 <Method_Signatures>;

}

Example:

package simplilearn;

public interface Area {

 public void Square();

 public void Circle();

 public void Rectangle();

 public void Triangle();

}

//Class



package simplilearn;

import java.util.Scanner;

public class shapeArea implements Area {

 public void Circle() {

  Scanner kb = new Scanner(System.in);

  System.out.println("Enter the radius of the circle");

  double r = kb.nextInt();

  double areaOfCircle = 3.142 * r * r;

  System.out.println("Area of the circle is" + areaOfCircle);

 }

 @Override

 public void Square() {

  // TODO Auto-generated method stub

  Scanner kb2 = new Scanner(System.in);

  System.out.println("Input the length of the side of the square");

  double s = kb2.nextInt();

  double areaOfSquare = s * s;

  System.out.println("Area of the square is" + areaOfSquare);

 }

 @Override

 public void Rectangle() {

  // TODO Auto-generated method stub

  Scanner kb3 = new Scanner(System.in);

  System.out.println("Enter the length of the Rectangle");

  double l = kb3.nextInt();

  System.out.println("Enter the breadth of the Rectangle");

  double b = kb3.nextInt();

  double areaOfRectangle = l * b;

  System.out.println("Area of the Rectangle is" + areaOfRectangle);

 }

 @Override

 public void Triangle() {

  // TODO Auto-generated method stub

  Scanner kb4 = new Scanner(System.in);

  System.out.println("Enter the base of the Triangle");

  double base = kb4.nextInt();

  System.out.println("Enter the height of the Triangle");

  double h = kb4.nextInt();

  double areaOfTriangle = 0.5 * base * h;

  System.out.println("Area of the Triangle is" + areaOfTriangle);

 }

 public static void main(String[] args) {

  shapeArea geometry = new shapeArea();

  geometry.Circle();

  geometry.Square();

  geometry.Rectangle();

  geometry.Triangle();

 }

}

Abstract Classes in Java

abstract-classes

An abstract class is almost identical to an interface, but the difference is, an abstract class can incorporate data members and their method definitions.

Syntax:

<Access_Modifier> abstract class <Name_of_the_class> {

 <Data Members>;

 <Data Methods>;

}

Example:

package Simplilearn;

public abstract class Person {

 private String Name;

 private String Gender;

 public Person(String nm, String Gen) {

  this.Name = nm;

  this.Gender = Gen;

 }

 public abstract void work();

 @Override

 public String toString() {

  return "Name=" + this.Name + "::Gender=" + this.Gender;

 }

 public void changeName(String newName) {

  this.Name = newName;

 }

 public void Exam() {

  // TODO Auto-generated method stub

  

 }

}

Class

package abstraction;

public class Employee extends Person {

 private int EmpId;

 public Employee(String EmployeeName, String Gen, int EmployeeID) {

  super(EmployeeName, Gen);

  this.EmpId = EmployeeID;

 }

 @Override

 public void Office() {

  if (EmpId == 0) {

   System.out.println("Employee Logged Out");

  } else {

   System.out.println("Employee Logged In");

  }

 }

 public static void main(String args[]) {

  Person employee = new Employee("Pavithra", "Female", 1094826);

  employee.Office();

  employee.changeName("Pavithra Tripathy");

  System.out.println(employee.toString());

 }

}

Encapsulation in Java OOPs Concepts

encapsulation

Encapsulation is a procedure of binding the data members and data methods together inside the user-defined class, which should be declared private.

Syntax:

<Access_Modifier> class <Class_Name> {

 private <Data_Members>;

 private <Data_Methods>;

}

Example:

package Simplilearn;

public class emp {

 public static void main(String[] args) {

  encapsule emp = new encapsule();

  emp.setName("Robert");

  System.out.println(emp.Name());

 }

}

package Simplilearn;

public class encapsule {

 private String empName;

 public String Name() {

  return empName;

 }

 public void setName(String empName) {

  this.empName = empName;

 }

}

//Output:

Robert

Inheritance in Java OOPs Concepts 

Inheritance is one of the object-oriented programming approaches that simplify software development. It enables the ability to build new classes by inheriting data members and methods, as well as the properties of previously defined classes.

The inheriting class is called a child/derived class, and the inherited class is called the parent/base class. The process of inheriting the parent/base class is carried out in different ways. We will now discuss each one of them in detail. 

Types of Inheritance

Single

single

Single inheritance consists of one parent class and one child class. Here, child classes inherit parent class methods and data members.

Example:

package inheritance;

class Student {

 void Play() {

  System.out.println("Playing Football...");

 }

}

class Bob extends Student {

 void Study() {

  System.out.println("Studying Physics...");

 }

}

public class Single {

 public static void main(String args[]) {

  Bob d = new Bob();

  d.Study();

  d.Play();

 }

}

Multi-Level

multi

Multi-level inheritance is also a parent-child inheritance relation, but the difference is another child class inherits the child class.

Example: 

package inheritance;

class Bike {

 public Bike() {

  System.out.println("Segment: 1000cc");

 }

 public void BikeType() {

  System.out.println("Bike Type: Sports");

 }

}

class NinJa extends Bike {

 public NinJa()

    {

  System.out.println("Make NinJa");

    }

 public void brand() {

  System.out.println("Manufacturer: Kawasaki");

 }

 public void speed() {

  System.out.println("Max Speed: 290Kmph");

 }

}

public class NinJa1000R extends NinJa {

 public NinJa1000R() {

  System.out.println("NinJa Model: 1000R");

 }

 public void speed() {

  System.out.println("Max Speed: 280Kmph");

 }

 public static void main(String args[]) {

  NinJa1000R obj = new NinJa1000R();

  obj.BikeType();

  obj.brand();

  obj.speed();

 }

}

Multiple

multiple

Java will not support multiple inheritance, as it ends up with a severe ambiguity.

Interface resolves the diamond problem.

Hierarchical 

hierchalical

Hierarchical inheritance is a parent-child relationship. The only difference is that multiple child classes inherit a single parent class.

Example:

package inheritance;

class Employee {

 double leaves = 25.00;

}

class PEmployee extends Employee {

 float totalHoursPerDay = (float) 8.00;

}

class TEmployee extends Employee {

 float totalHoursPerDay = (float) 10.50;

}

public class EmployeeSalary {

 public static void main(String args[]) {

  PEmployee permenant = new PEmployee();

  TEmployee temporary = new TEmployee();

  System.out.println("Permanent Employee Total Number of leaves are :\n" + permanent.leaves);

  System.out.println("Number of working hours for Permanent Employee are:\n" + permenant.totalHoursPerDay);

  System.out.println("Temporary Employee Total Number of leaves are :\n" + temporary.leaves);

  System.out.println("Number of working hours for Temporary Employee are :\n" + temporary.totalHoursPerDay);

 }

}

Hybrid

hybrid

The hybrid inheritance can be a combination of any of the three types of inheritances supported in Java.

package inheritance;

class C {

 public void Print() {

  System.out.println("C is the Parent Class to all A,B,D");

 }

}

class A extends C {

 public void Print() {

  System.out.println("A has Single Inheritance with C and shares Hierarchy with B");

 }

}

class B extends C {

 public void Print() {

  System.out.println("B has Single Inheritance with C and shares Hierarchy with A");

 }

}

public class D extends A {

 public void Print() {

  System.out.println("D has Single Inheritance with A and Multi-Level inheritance with C");

 }

 public static void main(String args[]) {

  A w = new A();

  B x = new B();

  C y = new C();

  D z = new D();

  

  y.Print();

  w.Print();

  x.Print();

  z.Print();

 }

}

Has-A Relation

When a class inherits an instance from a different class or an instance of its class, then the relation is a HAS-A type.

Example: Orange HAS-A citrus taste.

package inheritance;

class School {

 private String name;

 School(String name) {

  this.name = name;

 }

 public String SchoolName() {

  return this.name;

 }

}

class Student {

 private String name;

 Student(String name) {

  this.name = name;

 }

 public String StudentName() {

  return this.name;

 }

}

public class HasARelation {

 public static void main(String[] args) {

  School schl = new School("St.John's School");

  Student candidate = new Student("Tobey Marshall");

  System.out.println(candidate.StudentName() + " is an Ex-Student of " + schl.SchoolName());

 }

}

Is-A Relation

is-a

When a class inherits methods and members from different classes, then the relation is said to be an IS-A Relation.

Example: Orange IS-A Fruit. 

package inheritance;

import java.util.*;

class Customer {

 public String Name;

 public String City;

 Customer(String Name, String City) {

  this.Name = Name;

  this.City = City;

 }

}

class Bank {

 private final List<Customer> customers;

 Bank(List<Customer> customers) {

  this.customers = customers;

 }

 public List<Customer> TotalAccountsInBank() {

  return customers;

 }

}

public class IsARelation {

 public static void main(String[] args) {

  Customer C1 = new Customer("Raju", "Bangalore");

  Customer C2 = new Customer("Shiva", "Hyderabad");

  Customer C3 = new Customer("Sachin", "Mumbai");

  Customer C4 = new Customer("Prashanth", "Vizag");

  Customer C5 = new Customer("John", "Goa");

  List<Customer> Customers = new ArrayList<Customer>();

  Customers.add(C1);

  Customers.add(C2);

  Customers.add(C3);

  Customers.add(C4);

  Customers.add(C5);

  Bank ABCBank = new Bank(Customers);

  List<Customer> cust = ABCBank.TotalAccountsInBank();

  for (Customer cst : cust) {

   System.out.println("Name of the Customer : " + cst.Name + "\n" + "City : " + cst.City);

  }

 }

}

Polymorphism in Java OOPs Concepts 

Polymorphism is a Java programming language ability that is used to process an object, operator, and method in multiple ways based on the data type used, and the class implementing them. Many programming concepts explain the procedure of polymorphism in Java. 

Overloading 

overloading

The process of method overloading is achieved when a class has two or more methods with the same name, but the specific method is selected based on the number of parameters declared.

Example:

package polymorphism;

public class Addition {

 public int add(int x, int y) {

  return (x + y);

 }

 public double add(double d, double e, double f, double g) {

  return (d + e + f + g);

 }

 public double add(double a, double b) {

  return (a + b);

 }

 public static void main(String args[]) {

  Addition a = new Addition();

  System.out.println(a.add(25, 30));

  System.out.println(a.add(10.0, 15.0, 20.0, 25.0));

  System.out.println(a.add(127.5, 123.5));

 }

}

Overriding

/overriding

Method overriding is a procedure in which a child class is allowed to implement a specific class present in the parent class.

Example:

package polymorphism;

public class SuperKeyWord {

 public static void main(String[] args) {

  triangle two = new triangle();

  two.countsides();

 }

}

class square {

 int sides = 4;

}

class triangle extends square {

 int sides = 3;

 public void countsides() {

  System.out.println("Number of sides in square : " + sides);

  System.out.println("Number of sides in triangle : " + super.sides);

 }

}

Operator Overloading and Operator Overriding

Java does not support operator overloading, nor operator overriding. The designers of the Java programming language understood the ambiguities of operator overloading and operator overriding in the C++ programming language. Hence, to avoid the complications, they have opted not to include operator overloading and operator overriding.

Static Polymorphism

Static polymorphism/compile-time polymorphism is executed during the compilation stage. Here, the overloading method is resolved in the compilation stage.

Dynamic Polymorphism

Dynamic polymorphism/run-time polymorphism is handled during the program execution stage. Here, the overriding method is resolved in the execution stage.

Super Keyword

The term "super" is a predefined keyword in Java that refers to the immediate parent class object or method defined in the program. In this procedure, whenever you create an instance of a subclass, then an instance of the parent class is also automatically created. The super reference variable will implicitly refer to that.

Example:

package polymorphism;

public class SuperKeyWord {

 public static void main(String[] args) {

  triangle two = new triangle();

  two.countsides();

 }

}

class square {

 int sides = 4;

}

class triangle extends square {

 int sides = 3;

 public void countsides() {

  System.out.println("Number of sides in square : " + sides);

  System.out.println("Number of sides in triangle : " + super.sides);

 }

}

Access Modifiers in Java OOPs Concepts

access-mod

In object-oriented programming, the language offers accessibility to the object, method, and data member based on the access specifier defined. Similarly, in the Java programming language, we have four different access specifiers. 

Default

If the programmer does not provide the access specifier, the compiler will consider the default access specifier. In Java, the default access is public. However, this access is limited to the current package that the user is working on. The following is a visual coding example that can help to clarify this process: 

Example:

package abc;

public class Sum {

 int add(int x, int y) {

  return x + y;

 }

}



package xyz;

import abc.Sum;

public class Access {

   public static void main(String args[]){

 Sum obj = new Sum();

 obj.add(67, 129);

   }

}



//Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

 The method add(int, int) from the type Sum is not visible

 at xyz.Access.main(Access.java:10)

Public

The public access specifier provides access to the data members, methods, and objects universally.

Considering the same example, if we just change the visibility to add() to the public, we can execute it without any \ errors.

Example:

package abc;

public class Sum {

 public int add(int x, int y) {

  return x + y;

 }

}



package xyz;

import abc.*;

public class Access {

 public static void main(String args[]) {

  Sum s = new Sum();

  System.out.println(s.add(67, 129));

 }

}

Protected

The protected access specifier provides access to the data members, methods, and objects if the subclasses trying to access them are in the same package where the protected data is defined. Otherwise, the outside class should be extending the protected class, or else they will be inaccessible. 

Example:

package abc;

public class Sum {

 protected int add(int x, int y) {

  return x + y;

 }

}

package xyz;

import abc.*;

class Access extends Sum {

 public static void main(String args[]) {

  Access obj = new Access();

  System.out.println(obj.add(323, 223));

 }

}

//output:

546

Private

The access for private specifiers strictly limits the access of the variables and methods to only the class in which they are declared. Outside of that, they cannot be accessed.

Example:

package xyz;

class Parent {

 private double x = 25;

 private int cube(int p) {

  return p * p * p;

 }

}

public class Access {

 public static void main(String args[]) {

  Parent object = new Parent();

  System.out.println(object.x);

  System.out.println(object.cube(10));

 }

}

//Output:

Compile Time error

Method Calling in Java OOPs Concepts

Java only supports call by value. Here, we pass the values to the specific method, and then after the implication of the method, we get the expected results.

For example:

package xyz;

public class Value {

 public static void main(String[] args) {

  int num = 25;

  change(num);

  System.out.println(num);

 }

 public static void change(int num) {

  num = 100;

 }

}

//Output: 25

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Conclusion

We hope that this comprehensive tutorial about OOPs concepts in Java will help you understand the basics of this part of the super-pervasive programming language

Want to Become a Certified Java Developer?

Are you interested in learning more about OOPs concepts in Java and getting certified as a professional Java developer? Check out our Java Certification Training Course, which has been curated by some of the most experienced experts across all industries. 

If you have any questions about OOPs concepts in Java, please feel free to ask them in the comments section.  We'll have our experts answer them for you! 

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.