10.HOW OOPS PRINCIPLES ARE IMPLEMENTED IN JAVA

Introduction

From our previous chapter, we studied OOPS theoretically. In this chapter, we will see how OOPS is implemented in Java. Java is an object-oriented programming language. So it provides various programming constructs to demonstrate the behaviour of an object.

Just like everything in our real world is an object, we have class and object here in Java. Class is nothing but the type of the object. In Java, object alone has no meaning as it is always of some class type.

In real world, also any object is of some type or group or class. For example, Bill Gates is an object of Man type. Melinda is an object of Woman type. Mars is an object of Planet type. Parrot is an object of Bird type.

Similarly, in Java, we define that “type” by writing class.

class Car
{
    String colour;
    String regNo;
    String makeNModel;
    // methods
}

This class definition just tells me the “type” of the object it represents. How to represent objects of this class? Well like this

Class Run Car
{
PSVM(String[] args)
{
Car mercedesOfJohn = new Car();
}

Also in this way we created an object in Java as there is an object (Car of John) standing in S John. Basically C road with…


Creating Objects in Java

So, what will we say here? John Car is an object of Car type. Where Car is a class. We defined. While creating this object, we can define different attributes of the Car object.

John Car’s so that the object, we can define different attributes of the Car object like color, regNo, makeNModel…

John Car:

Similarly, we can create as many objects of the Car type as we want.

java

Car samCar = new Car ("White", "UP2801A1111", "Maruti 800");
colour: White
regNo: UP2801A1111  
makeNModel: Maruti 800

Sam Car


Object Instantiation (Constructor Concept)

NOTE: The constructor we saw in the beginning is called default constructor. We never need to add write that constructor. Java automatically creates a default constructor behind the scene. But if we provide a constructor explicitly, if C actually parameterized constructor, then C uses our constructor.

Did You Know?

Have a look at the definition of parameterized constructor once you saw. You know what? You could write this parameterized constructor like the C in Java would never be complained or get confused.

class Car:

java

String colour;
String regNo;
String makeNModel;
Car (String colour, String regNo, String makeNModel)
{
    this.colour = colour;
    this.regNo = regNo;
    this.makeNModel = makeNModel;
}

This would raise electrifyError confusion to Java (JVM) and that’s why Java has provided the “this” keyword to avoid this confusion. “this” will refer to the current object we are creating.


Local Variables vs Class Variables

Now we all already talking so much, let’s get aware of local & global variable.

So the argument variable we used strictly, i.e. then S scope is limited to that next constructor only will outside the constructor. So if you try to print these variables (Car access) outside this method it will throw an error.

On the other hand, class variables are global variables – they can be accessed anywhere in the class.

When we create the object in Java, the same is created in the heap area of the memory. Inside the heap, this memory is allotted every time when class file is executed by CPU.


Encapsulation

Definition

Encapsulation is wrapping up of data (variables) and function (methods) together in a single unit (called class). Aside from this is what we already observed. Isn’t it? The class data encapsulates within it data in the form of class variables when will store attributes value. Functions/the methods which we write within the class. Any single encapsulate of class can be.

Example:

java

class StdStudent
{
    String colour;
    String regNo;
    String makeNModel;
    // Keep default constructor
    public void doStudent (String colour)
    {
        SOP.ln("This object steals jewellery");
    }
}

See here a short…

We see two special characters? & : Condition is put before “?”. If true the statement before “:” is read/created. If false, the statement after “?” is executed.

Hence, we can access the method of Parent in Child class (condition apply) but owner may not be true. We will study about the condition soon.

Let’s see invoking of methods.

class TestVehicular:

java

PSVM(String[] args) throws Exception
{
    Vehicle vehicle = new Vehicle();
    // not allowed check yourself
    
    Vehicle vehicleObjectx = new Car();
}

So in the previous example, Road Ramp Dept can expose an abstract class instead of interface. If they want the common D like you to see the

Clarify the four idea:


Abstraction

Definition

The definition of this principle is: The act of representing essential features without including the background details. In real world object we clearly see this principle followed, both by the ones created by God and by humans.

We don’t see the kidney, lungs, brain of a dog. We don’t see the engine, piston, axle etc of a car. Similarly in Java data abstraction is achieved through the concept—interface and abstract class.


Interface

In Java, interface looks like class with only difference that the methods are not declared. But not defined.

Interface Car:

java

void sum(); // No definition or declaration.

Inheritance

Definition

One of the most important and popular principles of OOPS. Java implements this principle beautifully. This concept is similar to the how people inherit wealth, health, character, knowledge, skills, etc. from their parents.

Analogy:

Alia Bhatt, for example, inherited lots of opportunities from her father Mahesh Bhatt who was a successful film maker. Ram Agarwal where father is a cloth businessman in the heart of the city will inherit all the wealth of his father. (Sir him, Ramesh Kumar) where father is a labourer will inherit the poverty from his parent. He will have to define his own attributes and behaviour to become a successful object.

In biology, we have read that a human is reproduced when the sperm (father’s cell) meets the ovum (mother’s cell). Human formed ultimately has attributes and behaviour from his parents. Some of them from his father and some of them from his mother. Additionally, each can develop his own attribute and behaviour. Somewhat like the logos in Java. An object could be a child object of a parent object.

class Parent:

java

String colour;
String height;
boolean isHumble();
boolean doTDS();
SOP("I do hobby job");

Types of Inheritance

Java supports three types of inheritance:

1) Single Inheritance

It’s the case where one parent class and one child class are involved. The example we just saw is single inheritance.

Parent class
    ↑ extends
Child class
10.1

2) Multilevel Inheritance

It’s like you, your parent, and your grandparent and so on. Here there are more than two classes involved where each class is related to other the adjacent class by single inheritance.

10.2
Class 1
    ↑ extends
Class 2
    ↑ extends
Class 3
    ↑ extends
class GreatParent

public void doByJob ():

java

SOP("I do byJob job");

3) Hierarchical Inheritance

This is the case where one class is inherited by more than one class.

Array Analysis:

A parent can have many children & each child inherits qualities from the parent.

10.3
Parent-1
    ↑ extends
[Class1] [Class2] [Class3]... Scor

Remember: trick includes are expanding horizontally in multi-level inheritance classes are expanding vertically.

If-don hierarchical:

Let’s understand through an example class Parent:

java

void doJob()
{
    SOP("I do banking job");
}

class Child1 extends Parent:

java

void playGuiter()
{
    SOP("I play guitar");
}

class Child2 extends Parent:

java

void playCricket()
{
    SOP("I play cricket");
}

Polymorphism

Definition

The word polymorphism is derived from two greek words – “poly” meaning many and “morph” meaning form. Hence collectively it means of many forms.

Let’s see how polymorphism is observed in real world objects.

Your smart TV is a real world object which exhibits polymorphism. How? It has a single behaviour – to show serial (Soy).

But this behaviour can be exhibited by your TV in more than one way:

  1. TV mode – where you tune in to a TV channel to see the serial
  2. App mode – where you tune in to an OTT app to see the same serial

Don’t you think TV object has many forms.

Mobile is another example of polymorphic object. It has single behaviour (keep communicating with other) but this can be achieved through two ways – call (2) SMS (3) Video call.

Another example of polymorphism is you and your father. You are an object. Your father is also an object. You are the sub-class of your father object.

Recall from the inheritance concept, so you also exhibit a behaviour of eating & your father also exhibit the same behaviour. However, if your behaviour of eating involves eating with right hand & your father’s behaviour is eating with left hand.


Abstraction via Class Plane

Show full implementation of Encapsulation using a class Plane:

Data Abstraction

The definition of this principle is: The act of representing essential features without including the background details. In real world object we clearly see this principle followed, both by the ones created by God and by humans.

We don’t see the kidney, lungs, brain of a dog. We don’t see the engine, piston, axle etc of a car. Similarly, in Java data abstraction is achieved through the concept – interface and abstract classes.


Interface

In Java, interface looks like class with only difference that the methods are not declared but not defined.

Interface Car:

java

void sum(); // No definition or declaration.

About Classes

In interface, one of the methods can be defined. It is a head restriction. Here there is another option called abstract class which has uses restriction—this class can have one of both methods:

  1. Methods which are only declared
  2. Methods which are defined

Analogy:

Take AUTO will say – I am an object of Vehicle type, i.e. I belong to Vehicle class.

Luxury Access will say – I am an object of Vehicle type.

Yes, they both are correct. But saying they are of Vehicle class will not be appropriate to say that it belongs to CAR class because although they exhibit several common behaviour like running on 4 wheels, other runs on 4 wheels, one has air and runs one on petrol, other runs on desk.

Hence, it would be more appropriate to say that it belongs to CAR class.

Because all objects of CAR show much similar behaviour among themselves.

Similarly, for Luxury Access, it would be appropriate to say that it belongs to Bike class!


In This Way, Vehicle is an Abstract Class

class TV:

java

void showSerial (String channelNo, String serialName)
{
    SOP("You are watching serial on TV mode");
}

void showSerial (String otApp) Date serial Name
{
    SOP("You are watching serial on OTT app");
}

As you can see, class TV defines two methods with exactly same method name but different (no of arguments, and/or different data type of argument and/or different order of argument. This is called “function/method overloading”. That means when we define methods with the same name (more then once) and in each such method no (of arguments and/or type of argument/or different order of argument.


Polymorphism Implementation

This is one practice how we achieve polymorphism.

Same method no with different no of arguments and/or different data type of argument and/or different order of argument:

X NOTE: Just changed the return type without changing any of the above three never reduces.


Let’s try to test the TV class methods

class TestTV:

java

PSVM(String[] args)
{
    TV myTV = new TV();
    @  myTV.showSerial ("Sony Lab", "2000");
    @  myTV.showSerial ("Sony LEPlay");
}

During complete of this program, at JVM will know you each statement (@ & @), which method in class TV will be invoked. That means when we will convert our Java into class at the time it will find the statement @ and @ with the corresponding method in class TV. How can I do she about this?

Just write the third line: @ myTV.showSerial (“0”, “B”, “C”, “9”) Compile (o just save)

It will give you complete error.

And that’s why method overiding (aka early binding or early binding) or compile and is also called…

There is another way of how polymorphism is implemented in (Class) Father

java

void eat()
{
    SOP("Eats with right hand");
}

class Son extends Father:

java

@Override
void eat()
{
    SOP("Eats with left hand");
}

Here we have two classes where one is child class of other. Both the classes have exactly same method signature – i.e. type of argument no of argument and the order of argument. This is called “function/method overloading”. This is how another way as we achieve polymorphism.

Let’s try to test this class:

class TestFatherSon:

java

@  Father david = new Father();
@  david.eat();
@  Father john = new Son();
@  john.eat();

In @, is david is an object of Father reference also.

In @, john is an object of Father reference.

But in @ & @, when eat() method will be called will not be decided at compile time but at runtime.

Have a look at line @ I @ quickly. The time on statement on RHS (is) to means that create an object which is done during compile time. The object create hopped in Spread plane of memory called heap during the execution.

So in @, an object of Father class is created & been eat() method of Father class is invoked.

In @, an object of Son class is created @ Although the reference is G to Father class is valid since Father is parent class of Son. Here in @, eat() method of Son class is invoked.

So as in the case of method overridden instance we also called late binding or dispatch binding.

Previous Article
Next Article