0% found this document useful (0 votes)
16 views23 pages

Oops What Is OOPS?: - Ajay Wankhade

The document provides an overview of Object Oriented Programming (OOP), including its definition, advantages, and key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction. It explains various types of inheritance, access modifiers, constructors, and the differences between classes and structures. Additionally, it discusses limitations of inheritance, the reasons Java does not support multiple inheritance, and the role of garbage collection in memory management.

Uploaded by

flowingcoder7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views23 pages

Oops What Is OOPS?: - Ajay Wankhade

The document provides an overview of Object Oriented Programming (OOP), including its definition, advantages, and key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction. It explains various types of inheritance, access modifiers, constructors, and the differences between classes and structures. Additionally, it discusses limitations of inheritance, the reasons Java does not support multiple inheritance, and the role of garbage collection in memory management.

Uploaded by

flowingcoder7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

- Ajay Wankhade

OOPS
=====
What is OOPS?
Object Oriented Programming is a programming paradigm in which
programs are considered as a collection of objects. Each object is nothing
but an instance of a class.
Alan Kay developed the first object oriented programming language.

What are some advantages of using OOPs?


OOP is very helpful in solving very complex problems.
- Highly complex programs can be created, handled, and maintained
easily using object-oriented programming.
- OOPs promote code reuse, thereby reducing redundancy.
- OOPs also help to hide the unnecessary details with the help of Data
Abstraction.
- OOPs are based on a bottom-up approach, unlike the Structural
programming paradigm, which uses a top-down approach.
- Polymorphism offers a lot of flexibility in OOPs.

What is Class and Object ?


Class :
● A class is a building block of Object Oriented Programs. It is a
user-defined data type that contains the data members and member
functions that operate on the data members. It is like a blueprint or
template of objects having common properties and methods.
● Example : Imagine a car manufacturing company. The company has
a blueprint for a car that defines the properties and methods that
every car should have. This blueprint is the class.

Object :
● An object is an instance of a class. Data members and methods of a
class cannot be used directly. We need to create an object (or
- Ajay Wankhade

instance) of the class to use them. In simple terms, they are the
actual world entities that have a state and behavior.
● When the company manufactures a car using the blueprint, the
actual car produced is an object. Each car produced from the
blueprint is an instance of the car class.

What are pillars of OOPs ?


i. Abstraction
ii. Encapsulation
iii. Polymorphism
iv. Inheritance
What is data hiding ?
Data hiding is a fundamental concept in object-oriented programming
(OOP) that refers to restricting access to the internal state of an object and
only allowing access through a well-defined interface. The main goal of
data hiding is to encapsulate the internal representation of an object and
protect it from unintended or unauthorized access and modification.

What is Abstraction ?
● Hiding internal implementation and just highlighting the set of
services is called abstraction.
● By using abstract classes and interfaces we can implement
abstraction.
● Example : An ATM machine provides an interface for users to perform
transactions like withdrawing money, checking balance, and
depositing money without exposing the internal operations of the
bank’s database.
● In other words, we can say that abstraction is a mechanism to show “
what is does” to user but to hide “how it does” from user.

What is Encapsulation ?
- Ajay Wankhade

● It is the process of Encapsulating data and corresponding methods


into a single module.
● If any java class follows data hiding and abstraction such type of
class is said to be an encapsulated class.
● It restricts direct access to some of the object components which
protects integrity of the data.
● Ex : Employee management system keeps track of employees
personal details like id, name, salary etc . It only allows changes
through specific methods to ensure data integrity.

Tightly Encapsulated Class ?


A class is said to be tightly encapsulated if and only if every variable
of that class is declared as private.

What is Polymorphism ?
● One entity having multiple forms is the concept of polymorphism.
● Polymorphism is the ability of objects of different classes to respond
to the same method call in different ways. It allows methods to do
different things based on the object it is acting upon, even though
they share the same name
● Can be achieved through overloading and overriding.
● Ex : A person can be an employee, a parent, or a friend. The behaviour
of the person varies based on the role they are in, but the person
remains the same.

What are types of Polymorphism ?


● There are two types:
1. Compile Time Polymorphism
2. Runtime Polymorphism
- Ajay Wankhade

What is Method Overloading ?


● Having the same name and different argument types is called method
overloading.
● Two methods are said to be overloaded if and only if both have the
same name but different argument types.
● In overloading, the compiler is responsible to perform method
resolution(decision) based on the reference type. Hence overloading
is also considered as compile time polymorphism/static/early
binding.

What is Method Overriding ?


● Whatever the Parent has by default available to the Child through
inheritance, if the Child is not satisfied with Parent class method
implementation then Child is allowed to redefine that Parent class
method in Child class in its own way this process is called overriding.
● The Parent class method which is overridden is called the overridden
method.The Child class method which is overriding is called the
overriding method.
● In overriding method resolution is always taken care by JVM based
on runtime object hence overriding is also considered as runtime
polymorphism or dynamic polymorphism or late binding.
Note: In overriding runtime objects will play the role and reference
type is dummy.

The process of overriding method resolution is also known as dynamic


method dispatch.

What is upcasting and downcasting ?


Upcasting/Generalization :
● It is a process of converting child class reference into parent type i.e.
when a child class object is stored on parent type reference, then it is
called upcasting.
- Ajay Wankhade

● It is done by the compiler automatically so it is also called implicit


conversion.
Downcasting/Specialization :
● It is a process of converting parent class reference into child type i.e.
when a parent class type reference is stored on child type reference,
then it is called downcasting.
● It is not done by the compiler automatically it is achieved
programmatically by using typecast operator so it is called explicit
conversion . It can only be performed after upcasting.

What is Inheritance ?
● Inheritance is a mechanism in object-oriented programming where a
new class, known as a subclass or derived class, inherits the
properties and behaviors (methods) of an existing class, referred to
as a superclass or base class.
● Also called the IS-A relationship.
● Ex: A car can be considered as a superclass with general properties
such as color, model, and methods like start() and stop(). A sports
car can be a subclass that inherits these properties and methods but
also has additional features like turbo boost.
- Ajay Wankhade

What are Types of Inheritance ?

1. Single Inheritance :
● Single inheritance is when a class (subclass/child class) inherits from
only one superclass (parent class).
● Ex : A class "Dog" inherits from a superclass "Animal".
● A Car inherits from a Vehicle.The Vehicle class contains common
properties and methods such as `speed`, `fuel`, and `start()`.The Car
class inherits these properties and methods and may add specific
features like `playMusic()`.

2. Multiple Inheritance (Through Interfaces in Java)


● Multiple inheritance is when a class inherits from more than one
superclass. Note that Java does not support multiple inheritance
directly to avoid complexity and ambiguity. However, multiple
inheritance can be achieved using interfaces.
● A Smartphone inherits features from both a Camera and a
Phone.Camera Interface: Contains methods like
- Ajay Wankhade

`takePhoto()`.Phone Interface: Contains methods like `makeCall()`.


Smartphone: Implements both Camera and Phone interfaces,
inheriting and combining their functionalities.

3. Multilevel Inheritance
● Multilevel inheritance is when a class is derived from a class
which is also derived from another class, forming a hierarchy of
classes.A Laptop inherits from a Computer, which in turn
inherits from an ElectronicDevice.ElectronicDevice: Contains
properties like `powerOn()` and `powerOff()`. Computer: Inherits
from ElectronicDevice and adds properties like `runProgram()`.
Laptop: Inherits from Computer and adds features like
`portable()`.

4. Hierarchical Inheritance
● Hierarchical inheritance is when multiple classes inherit from a single
superclass.
● Example : Animal (Superclass): Contains methods like `eat()` and
`sleep()`.Dog (Subclass): Inherits from Animal and adds `bark()`. Cat
(Subclass): Inherits from Animal and adds `meow()`.

5. Hybrid Inheritance (Combination of two or more types of


inheritance)
● Hybrid inheritance is a combination of two or more types of
inheritance. It can be a mix of hierarchical, single, multiple, or
multilevel inheritance.
● An ElectricCar class demonstrates hybrid inheritance by combining
hierarchical and multiple inheritance. Vehicle (Superclass): Contains
properties and methods like `speed`, `fuel`, and `start()`. Car
(Subclass): Inherits from Vehicle. Electric (Interface): Contains
methods like `chargeBattery()`. ElectricCar (Subclass): Inherits from
Car and implements Electric interface, thus combining both
hierarchical and multiple inheritance.
- Ajay Wankhade

Are there any limitations of Inheritance?


● Yes, with more powers comes more complications. Inheritance is a
very powerful feature in OOPs, but it has some limitations too.
Inheritance needs more time to process, as it needs to navigate
through multiple classes for its implementation. Also, the classes
involved in Inheritance - the base class and the child class, are very
tightly coupled together. So if one needs to make some changes, they
might need to do nested changes in both classes. Inheritance might
be complex for implementation, as well. So if not correctly
implemented, this might lead to unexpected errors or incorrect
outputs

Why java doesn’t support multiple inheritance ?


Because it can lead to ambiguity in the method resolution.
Ex: if a class inherits from two classes that have a method with the same
name , then the compiler will not know which method to call. This can lead
to ambiguity and errors and make the code difficult to maintain.

The diamond problem occurs when a class inherits from two classes that
have common methods. This can lead to a situation where the child class
has two copies of the same method, one from each parent class. The JVM
will not know which method to call and this can lead to errors.

Difference bw super() vs this() ?

this super

refers to current instance of the represents current instance of the


class. parent class

used to call default constructor of used to call default constructor of


- Ajay Wankhade

the same class parent class.

use to access methods of current can access methods of parent


class as it has reference of the class with the help of super.
current class

Ot cam be referred from static It can’t referred from static context


context i.e. can be invoked from i.e can’t be invoked form static
static instance, for instance we can instance. sop(super.x) -> CE/RE
write sop(this.x) which will print
values of x without CE/RE

What are Access modifiers ?


Access modifiers are keywords that are used to provide accessibility to
different types of members such as classes, methods,constructor and
fields. They control who can access and modify different parts of the code,
ensuring encapsulation, data security and code integrity
1. private : most restrictive modifier. Members can only be accessed
from within the same class theory are defined in.
2. default: If no access modifier is specified, the member has default
access: Members declared with default access are accessible only
within the same package.
3. protected :The protected access modifier allows access within the
same package and also to subclasses (even if they are in different
packages
4. public :
- Ajay Wankhade

The public access modifier allows members to be accessible from


any other class.

How much memory does a class occupy?


Classes do not consume any memory. They are just a blueprint based on
which objects are created. Now when objects are created, they actually
initialize the class members and methods and therefore consume memory.

Why is java not a pure obj oriented lang ?


In object oriented language everything is represented as objects. But in
Java we have primitive data types because with this we work with simple
data like number and char without creating their objects and avoid
unnecessary overhead.
This not only improves performance and simplifies basic data operations.
java also gives an option to convert primitive to object by using wrapper
classes.
Java strikes a balance between object oriented purity and practical
efficiency.

When an object is deleted or garbage collected in java ?


in java GC is responsible for deleting objects that are no longer being used.
The GC runs automatically and it is not necessary for programmers to
explicitly call it

Is it always necessary to create objects from class?


No. An object is necessary to be created if the base class has non-static
methods. But if the class has static methods, then objects don’t need to be
created. You can call the class method directly in this case, using the class
name

Are class and structure the same? If not, what's the difference between a
class and a structure?
- Ajay Wankhade

No, class and structure are not the same. Though they appear to be similar,
they have differences that make them apart. For example, the structure is
saved in the stack memory, whereas the class is saved in the heap memory.
Also, Data Abstraction cannot be achieved with the help of structure, but
with class, Abstraction is majorly used.

What are Constructors ?


● Constructor is a block similar to method having the same name as
that of class name.
● It does not have any return type, not even void, as constructor use to
initialize object which does not return anything and compiler will not
able to judge return type while creating default constructor.
● The only modifiers applicable for constructor are public, protected,
default and private
● Constructor executes automatically when we create an object.

Types of Constructor ?
1.Default Constructor ( 0-args constructor )
A default constructor is automatically generated by the compiler if no
constructor is explicitly defined in the class. It does not take any arguments
and simply initializes the object.
Real-life Example: Imagine a new employee joins a company, and they are
automatically assigned default values for their profile information like
"Name: Unknown" and "ID: 0"

2.No-Arg Constructor

A no-arg constructor is explicitly defined in the class and does not take any
arguments. It can be used to initialize the object with default or initial
values. Real-life Example: A bank account is created with a default balance
of $0 and no account holder name.

3.Parameterized Constructor
- Ajay Wankhade

A parameterized constructor is defined with parameters to initialize the


object with specific values provided at the time of creation.Real-life
Example: When registering for an event, you provide specific details like
name and email address.

4.Copy Constructor :

A copy constructor creates a new object as a copy of an existing object. It


is not provided by default in Java, so you need to define it explicitly if you
need it.What it means is that a copy constructor will clone an object and its
values, into another object, is provided that both the objects are of the
same class. Example: Duplicating an existing document with the same
content.

What is a destructor?
Contrary to constructors, which initialize objects and specify space for
them, Destructors are also special methods. But destructors free up the
resources and memory occupied by an object. Destructors are
automatically called when an object is being destroyed

Difference bw Constructors and Instance blocks ?


● Both instance block and constructor will be executed automatically
for every object creation but instance block 1st followed by
constructor.
● The main objective of the constructor is to perform initialization of an
object.
● Other than initialization if we want to perform any activity for every
object creation we have to define that activity inside instance block.
● Both concepts having different purposes hence replacing one
concept with another concept is not possible.
● Constructor can take arguments but instance block can’t take any
arguments hence we can’t replace constructor concept with instance
block.
Similarly we can’t replace instance block purpose with constructor.
- Ajay Wankhade

What is a static block ?


- Static blocks will be executed at the time of class loading hence if we
want to perform any activity at the time of class loading we have to
define that activity inside the static block.
- Within a class we can take any no. Of static blocks and all these
static blocks will be executed from top to bottom.
- Eg : Every JDBC driver class internally contains a static block to
register the driver with DriverManager hence programmer is not
responsible to define this explicitly

Without using the main() method is it possible to print some statements to


the console?
Yes, by using a static block.
class Google {
static {
System.out.println("hello i can print"); System.exit(0);
}}

Without using System.out.println() statement is it possible to print some


statement to the console?
class Test {
public static void main(String[] args) {
System.err.println("hello");
}

What are Sealed classes ?

Sealed classes in Java are a feature introduced in Java 15 (as a preview


feature) and finalized in Java 17. Sealed classes allow you to restrict which
classes or interfaces can extend or implement them. This feature provides
more control over the class hierarchy and helps in modeling your domain
- Ajay Wankhade

more precisely by explicitly specifying which classes are allowed to be


subtypes. Example :

public sealed class Shape permits Circle, Square, Rectangle { // class body }

What are class modifiers ?


Whenever we are writing our own classes, we have to provide some
information about our class to the jvm. Like
1) Whether this class can be accessible from anywhere or not.
2) Whether child class creation is possible or not.
3) Whether object creation is possible or not etc
The only applicable modifiers for Top Level classes are:
1. public :
If a class is declared as public then we can access that class from
anywhere.
2. default :
If a class declared as the default then we can access that class only
within the current package hence default access is also known as
“package level access”.
3. final :
If a class declared as the final then we cannot creates the child class
that is inheritance concept is not applicable for final classes.
4. abstract :
For any java class if we are not allow to create an object such type of
class we have to declare with abstract modifier that is for abstract
class instantiation is not possible
5. strictfp :
If a class declares as the Strictfp then every concrete method(which
has body) of that class has to follow IEEE754 standard for floating
point arithmetic. But we can declare a class with abstract and strictfp
modifier simultaneously. That is abstract strictfp combination is legal
for classes but illegal for method.
- Ajay Wankhade

Can we use static and abstract keywords together ?


No. Bcoz It is mandatory to override abstract method from child class and
static method can’t be overridden from child class.

What is the interface ?


A method without any body is called an abstract method.If a class contains
an abstract method then that class is AC. We can’t create objects of AC .

What is the interface ?


Any service requirement specification (srs) is called an interface.
Interfaces are the blueprint of the class. It specifies what a class must do
and not how.
They are similar to Abstract class but all the methods are of abstract type
and are used to achieve abstraction and loose coupling. We can achieve
multiple inheritance
Java 8 :
default concrete methods
static methods
private methods - java 9

Does the interface have variables?


An interface can contain variables to define requirement level constants.
Every interface variable is always public static and final whether we are
declaring or not.

What are types of interfaces ?


1. Normal Interface.
2. Marker Interface
3. Functional Interface

What is Marker Interface ?


An interface which does not contain any methods, fields, abstract methods
and any constants is called marker interface and by implementing that
- Ajay Wankhade

interface if our object gets some ability such type of interfaces are called
Marker interface (or) Tag interface (or) Ability interface
Eg : public interface Demo
{
//empty
}

Examples of Marker Interface ?


1. Cloneable
- java.lang package
- generates a replica of an object with diff name.
2. Serializable
a. java.io
3. Remote
- java.rmi
- It marks object as remote that can be accessed from host of
another machine.

Are there any alternatives to marker interface ?


Yes.
1. Internal Flags : used to implement specific operation.
2. Annotations: we can perform specific operation.

What is Functional Interface ?


● Functional interface can contain only one abstract method.
● They are introduced to invoke lambda expressions.
● Single Abstract Method Interface.
● als allows
1. Default methods
2. static methods
3. public methods from object class

Examples of Functional Interface ?


- Ajay Wankhade

1. Runnable :run()
2. Callable ; call()
3. Comparable :compareTo()

Can we have instance variable inside an Interface ?


No, we can’t have an instance variable/non static variable inside an
interface.

A variable inside a interface is by default public, static andfinal type variable


which must be initialized at the time of declaration.
Difference bw AC & interface ?
Interfaces are used to define a contract for a group of unrelated classes or
to provide a common behaviour for classes that are not related by
inheritance.
Use abstract classes when you have a group of related classes that share
common attributes and behaviours.
AC have abstract as well as concrete methods but I will by default abstract.
AC contains constructors I cannot

What is Type casting:


Parent class reference can be used to hold Child class object but by using
that reference we can’t call Child specific methods.
Similarly we can use interface reference to hold implemented class object.

What is Coupling:
The degree of dependency between the components is called coupling.
more dependency -> tightly coupling
less dependency -> loosely coupling

What is Cohesion:
For every component a clear well defined functionality is defined then that
ocmponent is said to be following high cohesion.
- Ajay Wankhade

promotes reusability of code,improves maintainablity of the applicaiton,


without affecting remaining comp we can modify any component

Shallow copy and deep copy :


A shallow copy of an object is a new object that is a copy of the original
object, but it only copies the references of the nested objects. It does not
recursively copy the objects that are referred to by the original object. This
means that both the original object and the shallow copy will refer to the
same nested objects.

A deep copy of an object is a new object that is a copy of the original


object, along with copies of all objects that are directly or indirectly referred
to by the original object. This means that the new object and the original
object are completely independent of each other, and modifying the nested
objects in one will not affect the other.
- Ajay Wankhade

Exception Handling
================
Exception:
An unwanted unexpected event that disturbs normal flow of the program is
called an exception.
It is highly recommended to handle exceptions. The main objective of
exception handling is graceful (normal) termination of the program.

What is the meaning of exception handling?


Exception handling doesn’t mean repairing an exception. We have to define
an alternative way to continue the rest of the program. Normally this way of
“defining alternatives is nothing but exception handling”.

Runtime stack mechanism:


For every thread JVM will create a separate stack all method calls
performed by the thread will be stored in that stack. Each entry in the stack
is called “one activation record” (or) “stack frame”. After completing every
method call JVM removes the corresponding entry from the stack. After
completing all method calls JVM destroys the empty stack and terminates
the program normally.

Exception hierarchy:
Throwable acts as a root for exception hierarchy. Throwable class contains
the following two child classes.
1. Exception: Most of the cases exceptions are caused by our program
and these are recoverable.
2. Error: Most of the cases errors are not caused by our program these
are due to lack of system resources and these are non recoverable.

Checked Vs Unchecked Exceptions:


The exceptions which are checked by the compiler for smooth execution of
the program at runtime are called checked exceptions.
1. HallTicketMissingException
- Ajay Wankhade

2. PenNotWorkingException
3. FileNotFoundException
The exceptions which are not checked by the compiler are called
unchecked exceptions.
1) BombBlastException
2) ArithmeticException
3) NullPointerException
Note: RuntimeException and its child classes, Error and its child classes are
unchecked and all the remaining are considered as checked exceptions.

Note: Whether exception is checked or unchecked, compulsory it should


occur at runtime only there is no chance of occurring any exception at
compile time.

Partially checked Vs fully checked:


A checked exception is said to be fully checked if and only if all its child
classes are also checked. Example:
1) IOException
2) InterruptedException

A checked exception is said to be partially checked if and only if some of its


child classes are unchecked.Example: Exception
The only partially checked exceptions available in java are:
1. Throwable.
2. Exception.
- Ajay Wankhade

Various methods to print exception information:


The Throwable class defines the following methods to print exception
information to the console.
1. printStackTrace(): This method prints exception information in the
following format.Name of the exception: description of exception
Stack trace
2. toString(): This method prints exception information in the following
format.Name of the exception: description of exception
3. getMessage(): This method returns only description of the
exception.Description.

Finally block:
It is never recommended to take clean up code inside try block because
there is no guarantee for the execution of every statement inside a try.
It is never recommended to place clean up code inside catch block
because if there is no exception then catch block won’t be executed.
We require some place to maintain clean up code which should be
executed always irrespective of whether exception raised or not raised and
- Ajay Wankhade

whether handled or not handled, such type of block is nothing but finally
block.Hence the main objective of finally block is to maintain cleanup code.

Return Vs Finally:
Even though return present in try or catch blocks first finally will be
executed and after that only return statement will be considered that is
finally block dominates return statement

Difference between final, finally, and finalize:


final:
Final is the modifier applicable for class, methods and variables. If a class
is declared as final then child class creation is not possible. If a method is
declared as final then overriding that method is not possible.

finally
It is the block always associated with try catch to maintain clean up code
which should be executed always irrespective of whether exception raised
or not raised and whether handled or not handled.

finalize:
It is a method which should be called by the garbage collector always just
before destroying an object to perform cleanup activities.
Note: To maintain clean up code finally block is recommended over
finalize() method because we can’t expect exact behaviour of GC.

throw statement:
Sometimes we can create exception objects explicitly and we can hand
over to the JVM manually by using throw keyword.
throws statement:
in our program if there is any chance of raising checked exception
compulsory we should handle either by try catch or by throws keyword
otherwise the code won’t compile Hence the main objective of “throws”
- Ajay Wankhade

keyword is to delicate the responsibility of exception handling to the caller


method.
throws” keyword required only checked exceptions. Usage of throws for
unchecked exception there is no use.
“throws” keyword required only to convenes complier. Usage of throws
keyword doesn’t prevent abnormal termination of the program.

Summary:
1) try: To maintain risky code.
2) catch: To maintain handling code.
3) finally: To maintain cleanup code.
4) throw: To handover our created exception object to the JVM manually.
5) throws: To delegate responsibility of exception handling to the caller
method.

You might also like