Beginners Programs :

Oops Concepts In Java – Tutorial With Examples | Oops

Oops Concepts in Java complete tutorial & Types with sample examples & Programs. Also check the complete Java tutorials right here.

There are different paradigms followed in writing programs (developing software) like the following…

  1. Sequential Programming.
  2. Procedure Oriented Programming.
  3. Object-Oriented Programming.
  4. Multi-tier Programming, etc

To develop better software, programmers and managers concentrate on the aspects like the following. These people ensure that the following features do exist in the software developed.

  1. Better User Interface: so that the end user feels more comfortable in using the software.
  2. Divisibility: comfortable division of work among programmers.
  3. Extendibility: so that it can be improved at a later stage.
  4. Modifiability: so that it can be modified with minimum effect on other parts of the code.

These 4 and other things can be achieved in a better way using Object Oriented Programming rather than the classic Sequential or Procedure Oriented Programming paradigms.

Core Oops Concepts are as follows:

  • Class
  • Object
  • Encapsulation
  • Data hiding
  • Abstraction
  • Polymorphism
  • Inheritance
  • Dynamic binding
  • Virtual mechanism

In fact, there are no standards to specify that a particular language is Object Oriented(Oops). It is agreed by most of the developers and followed. Generally, a language is said to be object-oriented(Oops) when it has the above features.

Example:

C++, Java, C#.net, Python, PHP, Perl

Even if a language does not contain 1 or more features but has most of the features, then it can be accepted as an object-oriented language.

Some languages have all the features but do not follow inheritance and dynamic binding. Such languages are known as object-based language.

Eg: Visual Basic

Some languages are treated as object-oriented but they do not contain classes. In such languages, objects are created based on functions/methods.

These languages are known as function-based object-oriented languages rather than class-based object-oriented languages.

Eg: JavaScript

A detailed explanation of each OOPS features:

These are the languages where the main concentration is on objects. Make a note of the following things:

  • When an object should be created,
  • how many objects should be created,
  • what operations can be performed on an object,
  • when a particular action should be taken by the object,
  • how an object interacts with other objects,
  • from what point an object is no longer required, etc.

These are the things a programmer should keep in mind while developing software using an object-oriented language.

Class:

A class is a base for all object orientation concepts(Oops). A class contains a set of variables and methods. A class provides a blueprint/plan for a set of objects. Once a class is defined we can create any number of objects based on it.

A class provides format and behaviour for its objects. The format is specified using data elements (variables) and behaviour is specified using functional elements (methods).

Example:

In the above example, we have created a class named Rect and it has 2 data elements (len and bre) and 3 functional elements (set, show and area).

When we create an object for the Rect object the object contains 2 data elements (len & bre) and the object can perform 3 actions (set, show and area). Each such object holds the same features.

Object:

The class and object are strongly related. Without a class, we cannot create an object. Once we have a class we create any number of objects. In the above example (class), we have created a class.

In fact, a class gives only specifications for its objects. It means memory is not actually allocated when we create the class.

  • But the actual amount of memory to be allocated (for each object) is decided by the class.
  • Suppose we create an object for Rect class, then a memory block of 8 bytes (the class has 2 int variables and size of int is 4 bytes in Java) is allocated.
  • If we create another object, then another memory block of same size (8 bytes) is allocated.
  • This way the actual memory allocation takes place only when objects are created.

When we create a Rect object with 10 and 20 as length and breadth, the corresponding object will be formed like

10 20

Similarly, when we create another object of the same class with 25 and 32 as data values, we will have an object like the following.

25 32

This way, whatever the number of objects created for a class, all such objects will have the same format.

An object is an instance of a class. In another way, an object is an example of a class. To understand it in a better way, think of the phrases “BarackObama is an example of President” and “BillClinton is an example of President”.

These phrases can be understood as “BarackObama is an instance of President” and “BillClinton is an instance of President”.

Pro-grammatically,  ‘President’ is a class and ‘BarackObama’ and ‘BillClinton’ are objects. When we think of a class, we think of a concept but not a physical reality.

This is similar to when we think of a ‘President’, we think of features that all Presidents posses but not a particular person. Once we have the concept of ‘President’ we can have any number of realities (objects) based on it.

There is no limit on the number of realities (BarackObama, BillClinton, GeorgeBush, etc).

An object is the programming representation of a real-time entity. It means, think of the above-mentioned example, suppose we want to store data of GeorgeBush who was a President.

What data (properties) of GeorgeBush should we store is decided in the corresponding class ‘President’. For that, we create a class like:

To store actual data of GeorgeBush, we need to create an object. When we create an object and store data the object will look like the following.

43 GeorgeWBush 2001 2009 Republican

 It means GeorgeBush (a real-time entity) is stored as data in an object. Similarly, when we create an object for BarackObama, one more memory block is created and it contains data like the following.

44 BarackObama 2009 2017 Democratic

Here, BarackObama (another real-time entity) is stored as an object. When we create an object, we can store data of a President. This way whenever we want to store data of a person (or any other entity) through a program, we need to create an object for it.

So we can say that the object is a programming representation of a real-time entity. It means DATA is stored in an OBJECT.

We should understand that object is data and data is an object. This is why object-oriented programming languages are also known as data-oriented programming languages. 

Encapsulation: 

The mechanism of wrapping the data elements and functional elements as a single unit is known as encapsulation. As we have been discussing class that it is a container that holds variables and methods, the class is again a key element here.

So we can say a class encapsulates variables and methods.

Object-oriented way

(variables & methods together)

Procedure-oriented way

(variables inside & methods outside)

                class Rect

                {

                                int l, b;

                               

                                void show()

                                {

                                }             

                                int area()

                                {

                                }

                }

                struct Rect

                {

                                int l, b;

                };

                void show(struct Rect r)

                {

                }             

                int area(struct Rect r)

                {

                }

In procedure oriented languages (like C-language), the containers (structures) can hold only data elements (variables). The functional elements (methods) should be written separately without any concern with the structures.

There, we cannot find a strong relationship between data and methods.

By watching the container (structures) we can understand the format of the object but cannot identify the behavior of the objects. Any code in the program can access the object data without any restriction.

So there was no proper control of ‘accessing data’ in procedure-oriented languages.

But in object-oriented languages, we can have clear boundaries about who can access/modify data and at what places the data may be modified, etc. So this mechanism is an important aspect of OOPS.

Data hiding: 

Providing security to elements of a class so that they are not accessed from unauthorized locations is the main these of data hiding. As we discussed earlier, object (data) is the thing that we concentrate on the most.

If it is accessed from everywhere, then controlling the program becomes difficult for the developer. This is one of the biggest problems found in procedure-oriented languages.

Because, once we create a structure, elements of it can be accessed from anywhere in the program. There is no control to restrict the access.

  • As a solution to this problem, object-oriented languages have keywords like private and protected.
  • When we make an element as private, it cannot be accessed outside the class boundary.
  • Only the methods in that class can access the elements.

Any entity outside the class cannot access such element. This is one kind of protection given to data (and of course to methods too).

If we make an element as protected, they can be accessed from anywhere in the current package but accessed in only child classes from other packages. This is another layer of protection.

With these kinds of facilities, the class developer has the freedom (and control) to allow only a limited group to access elements of the class.

Example:

Abstraction:

The provision of giving interface by hiding the internal implementation is known as Abstraction. To see the effects of abstraction, overriding and inheritance concepts should be involved.

Generally, the interface is provided by the parent class (or parent interface) and the actual implementation is provided by the child classes.

The user (a programmer that uses the interface) of the interface will concentrate on the provisions given by the parent but what class actually implements is not concerned to that user.

There may be the number of classes available to implement the interface and depending on the user requirements object of the concerned child class will be selected at runtime.

Example:

In the above example, Fruit provides the interface to the user. Based on the option taken an object of  Apple or Mango is created. This selection is not known by compilation time, it is known only at runtime.

But the user does not need to worry about the method of which class (Apple or Mango) should be invoked.

The user will just invoke the methods of Fruit and based on the object selected, methods of the corresponding class will be executed. As these details are hidden (abstracted) from the user and only the interface is provided.

In this example, we have specified the implementing classes.

Sometimes the implementing classes are not known at all to the user. The user just uses the methods of the corresponding interface and internally (without programmers knowledge) the methods of implementing classes will be executed.

Example:

Output:

In the above example, we have used Iterator interface and this interface has methods like hasNext() and next().

But the actual implementation is done by some other class and we need not concentrate on that implementing class. Internally the system will take care of creating the corresponding object.

With the statement Iterator<String> it=al.iterator();, the required internal operations are performed. This is what abstraction is.

  • Let us try to understand abstraction in some other way. Suppose you make a phone call to your friend.
  • For that what we do is “interaction”. What happens in the background is “abstraction”.
  • As part of “interaction”, we type the number or select friend’s name from contact list and dial.
  • So our phone is the interface device and the actions we perform are interaction.

Once we dial, so many things will take place like sending a signal, transmitting via some towers, checking our balance for making the call, validating the receiver number, and many more.

When everything is fine then the signal will reach to your friend and that friend can hear a ringtone. The entire things have taken place after we dial is known as “abstraction”. We do not need to concentrate on all these details.

Similarly, when we make a method call, we do “interaction”. How the method is invoked, what exactly is the code in that method, what concepts or objects used in that method, which version of the method is executed, etc are not concerned to us.

These internal things are known as “abstraction”. 

Polymorphism

Having multiple implementations for a single interface is known as polymorphism.

In procedure-oriented languages, we cannot have two methods with the same name even though their arguments differ. But in object-oriented languages, we can have multiple methods with the same name provided their arguments differ.

This mechanism is known as method overloading.

Example:

When inheritance is involved, a child class can have its own implementation for a method in its parent class. This mechanism is known as method overriding.

Example:

These concepts of ‘overloading’ and ‘overriding’ are examples for polymorphism. We cannot see these facilities in procedure-oriented languages. 

Inheritance:

The mechanism of acquiring features from existing classes into new classes is known as inheritance. With this, we can reuse the existing code in the best possible way instead of re-writing it. all child classes get features of its common parent class.

A class can get features from its parent class directly and gets features from grand-parent class and its parents indirectly.

After inheriting features from its parent, a child class can define its own features so that the child class will have more features compared with its parent class. If wanted, the child class can write its own meaning to the parent counterparts in its (child class) limits.

Example: 

With the above example, the features of Book are inherited into TextBook. So TextBook can use features of Book. In this, Book is parent/super/base class and TextBook is child/sub/derived class.

In Java, all classes are derived from the class Object. If we create a class without any parent class, then the system automatically inherits Object into that class. So the following two classes mean the same.

Example 1:

Example 2:

In Java, a class can have any number of child classes to it and the class cannot have multiple parent classes. But a class can have multiple parent interfaces.

Dynamic binding

When inheritance is involved, a parent class reference may refer any of its child class object. This reference may take place at runtime based on user input or some other event.

So the system does not bind the method invocation with a specific method of a class. The binding will take place at runtime when the actual object is confirmed.

The decisions taken at runtime are known as dynamic decisions and the corresponding activities are known as dynamic activities. In this context, the binding taken place at runtime is known as dynamic binding.

For dynamic binding to take place, inheritance, overriding, etc should be involved.