Trang chủ Lập trình Java OOPS Concepts In Java with Examples

OOPS Concepts In Java with Examples

0

Object-oriented programming is an approach to development and an organization that attempts to eliminate some of the flaws of conventional programming methods by incorporating the best of structured programming features with several new concepts. It involves new ways of organizing and developing programs and does not a concern using a particular language. Languages supporting OOP features include Smalltalk, Objective C, C++, Ada, Pascal, and Java. 

Definition of OOPS Concepts in Java

So we can define OOP programming as:

“Object-oriented programming is an approach that modularizes programs by creating a partitioned memory area for both functions and data that can be used as templates for creating copies of such modules on demand.”

OOPS Paradigm 

The primary objective of the object-oriented approach is to eliminate some of the pitfalls that exist in the procedural approach. OOP treats data as an element in the program, not allowing it to flow around the system freely. It ties data closely to the functions that operate on it and protects it from unintentional modification by other existing functions. OOPS allows decomposing a problem into several entities called Objects and then build data and functions from these entities. The combination of the data makes up an object. 

Object = Method + Data 

The data of an object is accessed by the methods associated with that object. However, the methods of an object can access methods of other objects. 

Features of OOPS

Some features of object-oriented programming in java are: 

  • Emphasis is on data than procedures
  • Programs are divided into objects
  • Data Structures are designed to characterize objects.
  • Methods operating on the data of an object are tied together in the data structure. 
  • Data is hidden, and external functions cannot access it. 
  • Objects communicate with each other through methods
  • New methods and data can be easily added whenever necessary
  • Follows the bottom-up approach in program design

List of OOPS Concepts in Java with Examples

General OOPS concepts in Java are

Objects and Classes 

Objects are runtime entities in an object-oriented system. An object can represent a person, a bank account, a place, a table of data. It may also represent user-defined data types like lists and vectors. Any programming problem is analyzed based on objects and how they communicate amongst themselves. The objects interact with each other by sending messages to one another when a program is executed. For Example, ‘customer’ and ‘account’ are two objects that may send a message to the account object requesting for the balance. Each object contains code and data to manipulate the data. Objects can even interact without knowing the details of each other’s code or data.

The entire set of code and data of an object can be made user-defined data type using the concept of the class. A class is a ‘data-type’ and an object as a ‘variable’ of that type. Any number of objects can be created after a class is created.

The collection of objects of similar types is termed as a class. For Example, apple, orange, and mango are the objects of the class Fruit. Classes behave like built-in data types of a programming language but are user-defined data types. 

Representation of an Object 

Data Abstraction and Encapsulation 

The wrapping up of the data and methods into the single unit is known as encapsulation. The data is accessible only to those methods, which are wrapped in the class, and not to the outside world. This insulation of data from the direct access of the program is called data hiding. Encapsulation of the object makes it possible for the objects to be treated like ‘black boxes’ that perform a specific task without any concern for internal implementation. 

Encapsulation- Objects as “black-boxes”

Abstraction is the act of reducing programming complexity by representing essential features without including the background explanations or details. Classes are the concept of abstraction and are defined as the list of abstract attributes such as size, weight, cost, and methods that operate on these attributes. Classes wrap or encapsulate all the essential properties of the objects that are to be created. 

Abstract classes and Abstract methods:

  1. An abstract class is a class with an abstract keyword.
  2. An abstract method is a method declared without a method body.
  3. An abstract class may not have all the abstract methods. Some methods are concrete. 
  4. A method defined abstract must have its implementation in the derived class, thus making method overriding compulsory. Making a subclass abstract avoids overriding. 
  5. Classes that contain abstract method(s) must be declared with abstract keyword.
  6. The object for an abstract class cannot be instantiated with the new operator. 
  7. An abstract class can have parameterized constructors.

Ways to achieve abstraction: 

  • Using abstract keyword
  • Using interfaces

Example Code: 

The code below shows an example of abstraction.

abstract class Car
{
 Car()
 {
  System.out.println("Car is built. ");
 }
 abstract void drive();
 void gearChange()
 {
  System.out.println("Gearchanged!!");
 }


class Tesla extends Car
 {
  void drive()
  {
   System.out.println("Drive Safely");
  }
 }

class Abstraction 
 {
  public static void main (String args[])
  {
   Car obj = new Tesla();
   obj.drive();
   obj. gearChange();
  }
 }

Inheritance 

Inheritance is the process by which objects of one class acquire some properties of objects of another class. Inheritance supports the concept of hierarchical classification. For Example, a bird Robin is part of the class, not a mammal, which is again a part of the class Animal. The principle behind this division is that each subclass shares common characteristics from the class from its parent class. 

Properties of Inheritance

In OOP, the idea of inheritance provides the concept of reusability. It means that we can add additional features to parent class without modification; this is possible by deriving a new class from the parent class. The new class consists of the combined features from both the classes. In Java, the derived class is also known as the subclass. 

Types of Inheritance 

  • Single 
  • Multiple 
  • Multilevel
  • Hybrid 

Example Code: 

The code below illustrates an example of Inheritance. 

class Animal 
{
 void eat()
 {
  System.out.println("I am a omnivorous!! ");
 }
}

class Mammal extends Animal 
{
 void nature()
 {
  System.out.println("I am a mammal!! ");
 }
}

class Dog extends Mammal 
{
 void sound()
 {
  System.out.println("I bark!! ");
 }
}

class Inheritance 
{
 public static void main(String args[])
 {
  Dog d = new Dog();
  d.eat();
  d.nature();
  d.sound();
 }
}

Polymorphism 

Polymorphism is an important OOP concept; it means the ability to take many forms. For Example, an operation exhibits different behavior in different situations. The behavior depends on the type of data used in operation. For Example, in the operation of addition, the operation generates a sum for two numbers. If the operands are strings, then a third-string is produced by the operation by concatenation. 

The figure below demonstrates that a single function name can be used to handle the different numbers and different types of arguments. 

In polymorphism, objects having different internal structures can share the same external interface; it means that a class of operation may be accessed in the same manner even though actions with each operation may differ. Inheritance extensively uses the concept of polymorphism. 

Polymorphism can be achieved in two ways:

Method Overloading 

It is possible to create methods with the same name but different parameter lists and different definitions. This is called method overloading. Method overloading is required when objects are required to perform similar tasks but using different input parameters. When we call a method in an object, Java matches up the method name first and then the number and type of parameters to decide which definition to execute. 

Method overloading is achieved in three ways:

On the Basis of Example 
Number of Parameters times(int, int)
times(int, int, int)
Data Types of Parameters times(int, int)
times(int, float)
The Sequence of Data Types of Parameters times(int, float)
times(float, int)

Example Code: 

The code below demonstrates the concept of method overloading.

class CircleArea 
{
 double area(double x)
 {
  return 3.14 * x;
 }
}

class SquareArea 
{
 int area(int x)
 {
  return x * x;
 }
}

class RectangleArea 
{
 int area(int x, int y)
 {
  return x * y;
 }
}

class TriangleArea 
{
 int area(int y, int x)
 {
  return (y * x)/2;
 }
}

class Overloading 
{
 public static void main(String args[])
 {
  CircleArea ca = new CircleArea();
  SquareArea sa = new SquareArea();
  RectangleArea ra = new RectangleArea();
  TriangleArea ta = new TriangleArea();

  System.out.println("Circle area = "+ ca.area(1));
  System.out.println("Square area = "+ sa.area(2));
  System.out.println("Rectangle area = "+ ra.area(3,4));
  System.out.println("Triangle area = "+ ta.area(6,3));
 }
}

Method Overriding 

A method defined in the superclass is inherited by its subclass and is used by the objects created by the subclass. However, there may be occasions when an object should respond to the same method but behave differently when that method is called, which means a method defined in the superclass is overridden. Overriding is achieved by defining a method in the subclass that has the same name, the same arguments, and the same return type as a method in the superclass. So, when the method is called, the method defined in the subclass invoked and executed instead of the one in the superclass. 

Example Code: 

The code below demonstrates the concept of method overriding.

class Shape 
{
 void draw()
 {
  System.out.println("Mention shape here");
 }

 void  numberOfSides()
 {
  System.out.println("side = 0");
 }
}

class Circle extends Shape 
{
 void draw()
 {
  System.out.println("CIRCLE ");
 }

 void numberOfSides()
 {
  System.out.println("side = 0 "); 
 }
}

class Box extends Shape 
{
 void draw()
 {
  System.out.println("BOX ");
 }

 void numberOfSides()
 {
  System.out.println("side= 6"); 
 }
}

class Triangle extends Shape 
{
 void draw()
 {
  System.out.println("TRIANGLE ");
 }

 void numberOfSides()
 {
  System.out.println("side = 3 ");
 }
}

class Overriding 
{
 public static void main (String args[])
 {
  Circle c = new Circle();
  c.draw();
  c.numberOfSides();

  Box b = new Box();
  b.draw();
  b.numberOfSides();

  Triangle t = new Triangle();
  t.draw();
  t.numberOfSides();
 }
}

Dynamic Binding 

Binding is the process of linking a procedure call to the code to be executed in response to the call. It means that the code associated with the given procedure call is not known until the time of the call at runtime. It is associated with inheritance and polymorphism. 

Message Communication 

Objects communicate with each other in OOPs The process of programming in case of OOP consists of the following:

  • Creating classes defining objects and their behavior.
  • Creating objects 
  • Establishing communication between objects.

The network of Objects Communicating with Each Other 

Specifying the object name, the method name, and the information to be sent is involved in message passing. 

For Example, consider the statement.

Objects can be created or destroyed as they have a life cycle. It allows communication between the objects until the objects are alive. 

Benefits of OOPs Concept in Java

  • Inheritance eliminates redundant code and enables reusability. 
  • As Message passing allows communication with objects, this presents writing code from scratch every time. It is thus saving development time and higher productivity. 
  • Partitions work in a project based on classes and objects.
  • Systems up-gradation is easy.

Applications of OOPs Concept in Java

  • Real-time systems
  • Simulation and modeling 
  • Object-oriented databases
  • Hypertext and Hypermedia
  • AI and expert systems
  • Neural networks and parallel programming 
  • Automation systems

Summary 

Java is a robust and scalable object-oriented programming language that is based on the concept of objects and classes. It offers features like inheritance, abstraction, encapsulation, and polymorphism for developing an efficient and reliable code. 

0 BÌNH LUẬN

BÌNH LUẬN

Vui lòng nhập bình luận của bạn
Vui lòng nhập tên của bạn ở đây

Exit mobile version