Oop AZEEM SUBHANI

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

What is Object Oriented Programming?

Object-Oriented Programming (OOPs) is a type of programming that is based on


objects rather than just functions and procedures. Individual objects are grouped
into classes. OOPs implements real-world entities like inheritance, polymorphism,
hiding, etc. into programming. It also allows binding data and code together.

Why use OOP?


• Code can be reused through inheritance thereby reducing redundancy
• OOPs allows data hiding; therefore, private data is kept confidential
• Problems can be divided into different parts making it simple to solve
• Easier for troubleshooting
• Flexibility through polymorphism

Struct vs class
• Class can create a subclass that will inherit parent's properties and methods,
whereas Structure does not support the inheritance.
• A class has all members private by default. A struct is a class where members
are public by default.
• Classes allow you to perform cleanup (garbage collector) before the object is
deallocated because the garbage collector works on heap memory. Objects
are usually deallocated when instance is no longer referenced by other code.
Structures cannot be garbage collector so no efficient memory management.
• Size of the empty class is 1 Byte whereas Sizeof empty structure is 0 Bytes.
• A structure is basically a user-defined collection of variables which are of
different data types.

Static keyword in Java?


The static keyword in Java is used for memory management mainly. We can apply
static keyword with variables, methods, blocks and nested classes. The static
keyword belongs to the class than an instance of the class.

Static Variables in a class: As the variables declared as static are initialized only
once as they are allocated space in separate static storage, so the static variables in
a class are shared by the objects. There can not be multiple copies of the same
static variables for different objects. Also because of this reason static variables can
not be initialized using constructors.
Static functions in a class: Just like the static data members or static variables
inside the class, static member functions also do not depend on the object of the
class. We are allowed to invoke a static member function using the object and the ‘.’
operator but it is recommended to invoke the static members using the class name
and the scope resolution operator.

Static Class: An instance of an inner class cannot be created without an instance


of the outer class. Therefore, an inner class instance can access all of the members
of its outer class, without using a reference to the outer class instance. For this
reason, inner classes can help make programs simple and concise.
Why is the Java main method static?
It is because the object is not required to call a static method. If it were a non-static
method, JVM creates an object first then call main() method that will lead the problem
of extra memory allocation

The difference between a static class and a non-static class is that a static class cannot be
instantiated or inherited and that all of the members of the class are static in nature.

What is the Final Keyword in Java?


Java final keyword is a non-access specifier that is used to restrict a class, variable,
and method. If we initialize a variable with the final keyword, then we cannot
modify its value.

If we declare a method as final, then it cannot be overridden by any subclasses.


And, if we declare a class as final, we restrict the other classes to inherit or extend
it.

In other words, the final classes cannot be inherited by other classes.


What is a Class?
A class is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one
type. In general, class declarations can include these components, in order:

1. Difference between class and object

CLASS OBJECT
A class is a blueprint from An object is the instance of the
which you can create the class, which helps
instance, i.e., objects. programmers to use variables
and methods from inside the
class.
A class is used to bind data as Object acts like a variable of the
well as methods together as a class.
single unit.
Classes have logical existence. Objects have a physical
existence.
A class doesn't take any An object takes memory when
memory spaces when a a programmer creates one.
programmer creates one.
The class has to be declared Objects can be declared several
only once. times depending on the
requirement.
Access Modifiers in Java
Accessing a member of a class depends a lot on the access levels or access
modifiers. Access modifiers provide access to members of a class within a Java
program.
In Java, there can be 4 access modifiers that can be used with classes, methods,
fields, and constructors:

• public
• default
• private
• protected
Constructor
Constructors are special methods without return value. Their name is always the
same as the name of the class; but they can accept parameters that help in setting
the initial state of the object, before the application starts using it.

If we do not provide any constructor, JVM assigns a default constructor to the class.
This default constructor does not accept any parameter.

Remember, if we assign a constructor to any class then JVM does not assign the
default constructor to it. If needed, we need to specify the default constructor
explicitly to the class.
Destructor
The destructor is the opposite of the constructor. The constructor is used to
initialize objects while the destructor is used to delete or destroy the object that
releases the resource occupied by the object.

Remember that there is no concept of destructor in Java. In place of the destructor,


Java provides the garbage collector that works the same as the destructor.
The garbage collector is a program (thread) that runs on the JVM. It automatically
deletes the unused objects (objects that are no longer used) and free-up the
memory. The programmer has no need to manage memory, manually. It can be
error-prone, vulnerable, and may lead to a memory leak.

Four Pillars of OOP:


In OOPs concepts, we will learn four major principles
– abstraction, encapsulation, inheritance, and polymorphism.

1. Abstraction is the process of exposing the essential details of


an entity, while ignoring the irrelevant details, to reduce the
complexity for the users.

2. Encapsulation is the process of bundling data and operations


on the data together in an entity.

3. Inheritance is used to derive a new type from an existing type,


thereby establishing a parent-child relationship.

4. Polymorphism lets an entity take on different meanings in


different contexts

Encapsulation is one of the four fundamental OOP concepts. The other three are
inheritance, polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting
on the data (methods) together as a single unit. In encapsulation, the variables of a
class will be hidden from other classes, and can be accessed only through the
methods of their current class. Therefore, it is also known as data hiding.

Benefits of Encapsulation
• The fields of a class can be made read-only or write-only.
• A class can have total control over what is stored in its fields.

Abstraction
Data Abstraction is the property by virtue of which only the essential details are
displayed to the user. The trivial or the non-essentials units are not displayed to the
user. Ex: A car is viewed as a car rather than its individual components
Consider a real-life example of a man driving a car. The man only knows that pressing
the accelerators will increase the speed of a car or applying brakes will stop the car,
but he does not know about how on pressing the accelerator the speed is actually
increasing, he does not know about the inner mechanism of the car or the
implementation of the accelerator, brakes, etc. in the car. This is what abstraction is.
In java, abstraction is achieved by interfaces and abstract classes. We can achieve
100% abstraction using interfaces.

Objects are the building blocks of Object-Oriented Programming. An object contains


some properties and methods. We can hide them from the outer world through
access modifiers. We can provide access only for required functions and properties
to the other programs. This is the general procedure to implement abstraction in
OOPS.

What are the different types of abstraction?


There are two types of abstraction.

• Data Abstraction
• Process Abstraction
Data Abstraction
When the object data is not visible to the outer world, it creates data abstraction. If
needed, access to the Objects’ data is provided through some methods.

Process Abstraction
We don’t need to provide details about all the functions of an object. When we hide
the internal implementation of the different functions involved in a user operation,
it creates process abstraction.

Abstract classes and Abstract methods


1. An abstract method is a method that is declared without implementation.
2. An abstract class may or may not have all abstract methods. Some of them
can be concrete methods
3. A method defined abstract must always be redefined in the subclass, thus
making overriding compulsory OR either make the subclass itself abstract.
4. There can be no object of an abstract class. That is, an abstract class can
not be directly instantiated with the new operator.
5. An abstract class can have parameterized constructors and the default
constructor is always present in an abstract class.
Encapsulation VS Abstraction
The most important difference between Abstraction and Encapsulation is that
Abstraction solves the problem at design level while Encapsulation solves it
implementation level.

Abstraction is about hiding unwanted details while giving out most essential details,
while Encapsulation means hiding the code and data into a single unit e.g., class or
method to protect inner workings of an object from the outside world.

What is interface?
Interfaces allow you to specify what methods a class should implement. Interfaces
make it easy to use a variety of different classes in the same way. When one or
more classes use the same interface, it is referred to as "polymorphism".

Advantages of Abstraction
1. It reduces the complexity of viewing the things.
2. Avoids code duplication and increases reusability.
3. Helps to increase the security of an application or program as only
important details are provided to the user.
Inheritance
Inheritance is one of the most important concepts of Object-Oriented
Programming. Inheritance is the capability of one class to inherit capabilities or
properties from another class in Java. For instance, we are humans.

We inherit certain properties from the class ‘Human’ such as the ability to speak,
breathe, eat, drink, etc. We can also take the example of cars. The class ‘Car’ inherits
its properties from the class ‘Automobiles’ which inherits some of its properties
from another class ‘Vehicles’.

The super keyword


The super keyword is similar to this keyword. Following are the scenarios where the
super keyword is used.
• It is used to differentiate the members of superclass from the members of
subclass, if they have same names.
• It is used to invoke the superclass constructor from subclass.
The Types of Relations (Is-A, Has-A)

Inheritance:
Inheritance is “IS-A” type of relationship. “IS-A” relationship is a totally based on
Inheritance, which can be of two types Class Inheritance or Interface Inheritance.
Inheritance is a parent-child relationship where we create a new class by using
existing class code. It is just like saying that “A is type of B”. For example, is “Apple is
a fruit”, “Ferrari is a car”.
For better understanding let us take a real-world scenario. HOD is a staff member
of college.

Composition:
Composition is a "part-of" relationship. Simply
composition means mean use of instance variables
that are references to other objects. In composition
relationship both entities are interdependent of
each other for example “engine is part of car”,
“heart is part-of body”.

Association:

Association is a “has-a” type relationship. Association establishes the relationship


b/w two classes using through their objects. Association relationship can be one to
one, One to many, many to one and many to many. For example, suppose we have
two classes then these two classes are said to be “has-a” relationship
• if both of these entities share each other’s object for some work and at the
same time they can exists without each other’s dependency or both have
their own life time.

Aggregation

Aggregation is based is on "has-a" relationship. Aggregation is a special form of


association. In association there is not any classes (entity) work as owner but in
aggregation one entity work as owner. In aggregation both entities meet for some
work and then get separated. Aggregation is a one-way association.

Example

Let us take an example of “Student” and “address”. Each student must have an
address so relationship b/w Student class and Address class will be “Has-A” type
relationship but vice versa is not true (it is not necessary that each address contain
by any student). So, Student work as owner entity. This will be an aggregation
relationship.
Types of Relationships with code example

What are the limitations of inheritance?


• Increases the time and effort required to execute a program as it requires jumping
back and forth between different classes
• The parent class and the child class get tightly coupled
• Any modifications to the program would require changes both in the parent as well
as the child class
• Needs careful implementation else would lead to incorrect results

What Polymorphism?
The word Polymorphism can be broken into two words – ‘poly’ means ‘many’ and ‘morph’
means ‘forms. So, polymorphism means many forms.

Polymorphism is the ability for a data or message to be processed in more than one form.
It is a concept by which a single operation can be performed in multiple different ways.

Real-Life Examples of Java Polymorphism


A security guard outside an organization behaves differently with different people entering
the organization. He acts in a different way when the Boss comes and, in another way
when the employees come.

When the customers enter, the guard will respond differently. So here, the behavior of the
guard is in various forms, which depends on the member who is coming

Types of Polymorphism in Java


• Static/Compile Time polymorphism: When the compiler resolves the
polymorphism during the compilation of the program, then we call such
polymorphism as compile-time polymorphism or static polymorphism.
Sometimes we also call it static binding.

In Java, we can implement or achieve the compile-time/ static polymorphism


with the help of Method Overloading.
Method Overloading:
When a class has two or more than two methods which are having the same name but
different types of order or number of parameters, it is known as Method overloading. Java
allows a function to have the same name if it can distinguish them by their number and
type of arguments.
For example, the following functions are different in Java:

float divide(int a, int b){...}

float divide(float x, float y){...}

float divide (float a,int b) {...}

That is, the function divide() taking two int arguments is different from divide() taking
two float arguments, and also from divide() taking both int and float arguments. This is
called function overloading.

• Dynamic/Run-time Polymorphism: Runtime or dynamic Polymorphism is the


polymorphism which resolves dynamically at the runtime rather than compile-time
is called. We can also call it as dynamic binding or Dynamic Method Dispatch.

Since the method invocation is during runtime and not during compile-time, this
type of polymorphism is called Runtime or dynamic polymorphism.

Method Overriding:
In an object-oriented language, Method overriding occurs when a derived class provides a
specific definition of the method that is already present in its parent class. We say that the
function in the base class is being overridden

Characteristics of Polymorphism in Java


There are many other characteristics of Polymorphism in Java other than Method
Overloading and Method Overriding. They are as follows:

• Coercion
• Operator Overloading
• Polymorphic Variables or Parameters
Let’s discuss these characteristics in detail.

1. Coercion
Coercion in Polymorphism deals with implicit type conversion of one type of object
to a new object of a different type. The compiler performs coercion to prevent type
errors.
A common example of coercion of string “8” into an integer 8 or double 8.0 or
another example is- an integer and string concatenation.

2. Operator Overloading
Operator Overloading is a characteristic of a static polymorphism in which the
same operator or symbol behaves differently depending on the input context or
the type of operands.

For example, the plus operator + is used for both adding two numbers as well as
for concatenating the Strings. Also, operators like!, & and | are overloaded for
logical and bitwise operations. In both cases, only the type of arguments decides
the interpretation of the operator.

When + operator is used with numbers (integers and floating-point numbers), it


performs numeric addition. For example,
int num1 = 5;

int num2 = 10;

int sum = num1 + num2; // Output = 15

And when we use + operator with strings, it performs concatenation of two


Strings. For example,

String firstName = "Woody";

String lastName = "Sad";

fullName = firstName + lastName; // Output = WoodySad

Polymorphic Variables:
In Java, polymorphic variables are represented by the object or instance variables.
The reason is that any object variables of a class can have an IS-A relationship for
their own classes as well as with subclasses.
Output:
I am a Shape.
I am a Circle.

In the above example, we have created an object variable obj of the Shape class.
Here, obj is a polymorphic variable. It is because,

• In the statement, obj = new Shape(), obj refers to the object of the Shape
class.
• In the statement, obj = new Circle(), obj refers to the object of the Circle
class.
Advantages of Java Polymorphism
• Polymorphism allows a superclass to define methods that are common to all of
its derived classes while allowing subclasses to specify the additional
implementation of some or all of those methods.
• Method Overriding is supported by Dynamic Polymorphism which is a key
aspect of dynamic binding or run-time polymorphism.
• Polymorphism provides the ability to a method to do different things on the
basis of the object upon which it is acting.
.

Some Questions Of OOP:


What are virtual functions?
Virtual functions are functions that are present in the parent class and are
overridden by the subclass. These functions are used to achieve runtime
polymorphism.

What are pure virtual functions?


Pure virtual functions or abstract functions are functions that are only declared in
the base class. This means that they do not contain any definition in the base class
and need to be redefined in the subclass.

Types of constructors
Types of constructors differ from language to language. However, all the possible
constructors are:

• Default constructor
• Parameterized constructor
• Copy constructor
• Static constructor (doesn’t take any params)
❖ A static constructor is the piece of code used to initialize static data,
which means that a particular task needs to be executed only once
throughout the program. It is usually called automatically before any
static members referenced or a first instance is generated.
• Private constructor
❖ Private constructors in Java are accessed only from within the class.
You cannot access a private constructor from any other class. If the
object is yet not initialized, then you can write a public function to call
the private instructor. If the object is already initialized, then you can
only return the instance of that object. (Singleton Class)

What is a copy constructor?


A copy constructor creates objects by copying variables from another object of the
same class. The main aim of a copy constructor is to create a new object from an
existing one.

What is the use of ‘finalize’?

Finalize as an object method used to free up unmanaged resources and cleanup


before Garbage Collection(GC). It performs memory management tasks.

What is an exception?

An exception is an event, which occurs during the execution of a program, that


disrupts the normal flow of the program's instructions.

An exception (or exceptional event) is a problem that arises during the execution of
a program. When an Exception occurs the normal flow of the program is disrupted
and the program/Application terminates abnormally, which is not recommended,
therefore, these exceptions are to be handle

Exceptions provide a pattern to the error and transfer the error to the exception
handler to resolve it. The state of the program is saved as soon as an exception is
raised.

What is exception handling?

Exception handling in Object-Oriented Programming is a very important concept


that is used to manage errors. An exception handler allows errors to be thrown and
caught and implements a centralized mechanism to resolve them.
What is the difference between an error and an exception?

Error Exception
Errors are problems that should not be Conditions that an application might try
encountered by applications to catch

What is a try/ catch block?


A try/ catch block is used to handle exceptions. The try block defines a set of
statements that may lead to an error. The catch block basically catches the
exception.

What is a finally block?


A finally block consists of code that is used to execute important code such as
closing a connection, etc. This block executes when the try block exits. It also makes
sure that finally block executes even in case some unexpected exception is
encountered.

You might also like