Java Object and Class OOP Concepts

Object-oriented programming

Object Oriented Programming (OOP) is a paradigm shift from procedural programming like C.

In C, the code is divided into functions, and the code acts on data. Data is passed from one function to the other and can be accessed and manipulated from any part of a program, whether small or large.

Managing and debugging becomes difficult for reasonably large programs as data cannot be secured or protected by the language features. As the complexity and size of the programs grow, the difficulty of debugging and maintaining the code increases.

In object-oriented programming (OOP), data in one segment of the program may or may not be exposed to other segments and thus provides lots of advantages. Data manipulation by any part of the program is not a possibility in OOP and, therefore, can handle the complexity of large programs by language features. This is the basic objective of the shift from procedural to object orientation.

OOP's birth was to simplify a complicated requirement into some basic simple black boxes where each box is a different functionality or feature and can be written independently by a developer. Finally, when all the black boxes have been developed, then all of them can be put together in one single box and shipped to the customer for usage.

So basically, what we are trying to achieve in OOP is a bottom-up approach where the features are developed first and are then utilized across multiple places or domains in an application through references. This is called Code Reuse (write once and use it many times). Procedural programming, on the other hand, is a top-down approach.

In OOP, we come across two new terms: Class and Object. Class is the basic building block (the black box) in the program, and object is a reference to that block of code (class) which may be utilized across multiple other classes, etc., depending upon the requirement.

Objects and classes are an integral part of Java programs. A class contains the member variables and member functions. Member function in Java is known as a method. A class is a blueprint from which objects are created. The variables and methods of the objects are accessible based on the accessibility provided or the restrictions imposed (we will explain it in detail later).

Now, let's move to some simple OOP code examples to help you explain how it is written and what is the meaning of the constructs and terms. Understanding the basic principles of object-oriented programming is a prerequisite to learning Java programming.

Ex. 1 shows a simple illustration of a Java class Hello. A main() function is defined within the class which prints Hello World.

			

class Hello   // class is a keyword, and Hello is the class name
{
  // Program begins with a call to main() function.
  // Outputs Hello World
  public static void main(String args[])
  {
   System.out.println("Hello World");
  }
}

				

Ex. 1: Java Hello World program.

Another class named Sum has been defined in Ex. 2. Here, we have defined two variables (first and second) and a method display(). In its main() function, an object of the class Sum has been created and is used to print the sum of the two input values.

			

public class Sum {
  int first;    // member variable – public by default
  int second;    // member variable – public by default
  void display()  // member function or method – public by default
  {
    int total = first + second;
    System.out.println("Sum of the two numbers are: "+total);
  }
  public static void main(String args[])
  {
    Sum Obj = new Sum();  // An object named Obj is created from class Sum
    Obj.first=10;     // variable first initialized
    Obj.second=20;     // variable second initialized
    Obj.display();     // method display() called
  }
}

				

These two illustrations show the difference between Java and C in coding style.

Java Object and Class OOP Concepts

Object-oriented programming

Object Oriented Programming (OOP) is a paradigm shift from procedural programming like C.

In C, the code is divided into functions, and the code acts on data. Data is passed from one function to the other and can be accessed and manipulated from any part of a program, whether small or large.

Managing and debugging becomes difficult for reasonably large programs as data cannot be secured or protected by the language features. As the complexity and size of the programs grow, the difficulty of debugging and maintaining the code increases.

In object-oriented programming (OOP), data in one segment of the program may or may not be exposed to other segments and thus provides lots of advantages. Data manipulation by any part of the program is not a possibility in OOP and, therefore, can handle the complexity of large programs by language features. This is the basic objective of the shift from procedural to object orientation.

OOP's birth was to simplify a complicated requirement into some basic simple black boxes where each box is a different functionality or feature and can be written independently by a developer. Finally, when all the black boxes have been developed, then all of them can be put together in one single box and shipped to the customer for usage.

So basically, what we are trying to achieve in OOP is a bottom-up approach where the features are developed first and are then utilized across multiple places or domains in an application through references. This is called Code Reuse (write once and use it many times). Procedural programming, on the other hand, is a top-down approach.

In OOP, we come across two new terms: Class and Object. Class is the basic building block (the black box) in the program, and object is a reference to that block of code (class) which may be utilized across multiple other classes, etc., depending upon the requirement.

Objects and classes are an integral part of Java programs. A class contains the member variables and member functions. Member function in Java is known as a method. A class is a blueprint from which objects are created. The variables and methods of the objects are accessible based on the accessibility provided or the restrictions imposed (we will explain it in detail later).

Now, let's move to some simple OOP code examples to help you explain how it is written and what is the meaning of the constructs and terms. Understanding the basic principles of object-oriented programming is a prerequisite to learning Java programming.

Ex. 1 shows a simple illustration of a Java class Hello.A main() function is defined within the class which prints Hello World.

			

class Hello   // class is a keyword, and Hello is the class name
{
  // Program begins with a call to main() function.
  // Outputs Hello World
  public static void main(String args[])
  {
   System.out.println("Hello World");
  }
}

				

Ex. 1: Java Hello World program.

Another class named Sum has been defined in Ex. 2. Here, we have defined two variables (first and second) and a method display(). In its main() function, an object of the class Sum has been created and is used to print the sum of the two input values.

			

public class Sum {
  int first;    // member variable – public by default
  int second;    // member variable – public by default
  void display()  // member function or method – public by default
  {
    int total = first + second;
    System.out.println("Sum of the two numbers are: "+total);
  }
  public static void main(String args[])
  {
    Sum Obj = new Sum();  // An object named Obj is created from class Sum
    Obj.first=10;     // variable first initialized
    Obj.second=20;     // variable second initialized
    Obj.display();     // method display() called
  }
}

				

These two illustrations show the difference between Java and C in coding style.

Class and Object

As already discussed, Classes and Objects are the basic building blocks around which Java programs are built. They are basically a reflection of each other. An object's existence is because of a class and vice-versa. One cannot work without the other.

A class defines data and code that acts on the data by a set of member variables and member functions (methods) as seen in the Stack class (Ex. 3). Each object created from the class shares the same attributes and behaviour and is therefore called an instance of the class. Class is a logical entity, whereas an object is physical.

An object is also a self-contained piece of data and associated code for manipulating the data. Variables and functions are defined within the container of a shell and are protected from the outside world. They do not reveal anything except the part that is required to be shared with other classes.

As shown in the above two examples, code and data are bound together within a class to form a completely self-sufficient unit. Class is only a definition and definitely not an existence. When an object is created from the class by thenew()operator, it comes into existence in the real world (in our case - the computer memory). Class is a prototype, and objects are instances of the same.

We may also conceptualize or view class as a data type. For example, if Stack(referring to the Data Structure concepts) is a class, then the Java statement

Stack astack = new Stack(100);

creates an object astack as a Stack data type of size 100.

Ex. 3 shows a simple implementation of a Stack class and its use in another class Test.

			

class Stack {
  int a[];
  int i,j,ptr = -1;
  Stack (int size)
  {
    a = new int[size];
    j=size;
  }
  void push(int value) {
	if (ptr < j-1) a[++ptr] = value;
	else
	 System.out.println("Stack Full");
  }
  int pop() {
	if (ptr > -1) return a[ptr--] ;
	else {
	  System.out.println("Stack Underflow");
	  return 0;
	}
  }
}
class Class {
  public static void main(String args[]) {
    Stack astack = new Stack(100);
    astack.push(30);
    astack.push(40);
    astack.push(50);
    System.out.println(astack.pop());
    System.out.println(astack.pop());
    System.out.println(astack.pop());
  }
}

				

 

Abstraction

Abstraction is the main concept behind object orientation. In the real world, when we use any gadget, we tend to ignore its internal details. A user of a car doesn't care to know the internals of the car's engine. This is human nature, and it helps us to refrain from understanding the complexity that has gone into building that real-life object.

The object is visible to us, but its internal mechanisms are abstract to us. We only know how to use it by its exposed properties and actions. This is an abstraction.

Abstraction is a concept, whereas encapsulation is its implementation.

In the class object paradigm, we apply similar concepts and hide the internal details of a class from the user.

The user can create objects, pass values to the object and use the methods available to them. They are completely in the dark about its internal details and cannot figure out how the class has been developed.

This is the essence of object-oriented programming. It is a powerful approach for creating applications that help to manage the entire life-cycle of major software projects.

OOP has three main principles - Encapsulation, Polymorphism, and Inheritance. These three concepts, along with encapsulation, work together in object-oriented programming. We will discuss them one by one now.

Encapsulation

Encapsulation is a mechanism that binds data and code within a single unit to protect them from outside, just like a medical capsule which is a mix of many medicines. This single unit is a class. Since the purpose of a class is to encapsulate and hide complexity, we can attach access specifiers - private, public, or protected with the member variables and methods for this purpose.

Inheritance

Inheritance is the methodology by which a class inherits the properties and functionalities of another class. So, if class A is inherited from class B, then class A automatically receives the capabilities of class B. This is also an example of code reuse - class B code is reused in class A.

Polymorphism

We have discussed the concept of abstraction and its implementation through encapsulation. And then further reuse of the encapsulated data and code by inheritance. Polymorphism brings further elegance to the code, making the code more readable and maintainable.