You are on page 1of 28

Languages that Supports OOP:-

Java, C++, C#, Python, PHP, Ruby, Perl, Dart, Swift, Scala and Smalltalk.[1]

Languages that Do not Support OOP:-


 Assembler.
 C.
 FORTRAN.
 COBOL.
 Forth.
 Pascal

Class:-
It is a user-defined data type, which holds its own data members and member functions, it
represents the set of properties or methods that are common to all objects of one type.
Real life example:
Class is basically a blueprint in which the thing we want to be made is explained in which we
decide the properties and which functions/operations it will perform

Object:-
An Object is an instance of a Class. When a class is defined, no memory is allocated but when
it is instantiated (i.e. an object is created) memory is allocated.

What is Object Oriented Programming?


2 programming patterns → in OO way we follow a structured way and group together all
related functions and variables in a single structure which we name as class due to
which code management becomes really easy and we can avoid code redundancy.
Object-oriented programming aims to implement real-world entities like inheritance, hiding,
polymorphism etc. in programming. The main aim of OOP is to bind together the data and
the functions that operate on them so that no other part of the code can access this data
except that function.
What is OOP in real life? (sbse pehli baat ye k oop khud kia h)
Everything we see in real life is in structured and well grouped form. Nothing is present in
scattered form in real life. Everything is combination of some things and has its own
responsibilities/functions which they are performing. Because what basically is OOP, it is such a
programming pattern which follows the structured way itself in which related functions and
variables are grouped together to perform a specific task. E.g. we have mobile phones they are
also structured in a way if they were in scattered form no one would buy them in fact everything
we see in our world is in structured form because OOP itself is based on real life principles .
E.g. when we write code for our organization we write in structured way so that our organization
can like it. In short everything we do is for someone and that someone is us / humans and all
humans like structured approach, when we make website for our clients we always follow the
structured approach why? Because it is user friendly, easily manageable so that’s why all real
world objects follow OOP principles well logically OOP follows all real world principles not real
world Objects.
Why OOP?
Reason:
Before OOP procedural programming was used which is only good for very small projects, for
larger projects, management becomes difficult due to which we cant create a bunch of variables
everywhere and pass a bunch of variables to functions as arguments because such code
becomes spaghetti code/ scattered code and other parts of code can also access those
functions so for better management OOP is used.
Code ko smjna asaan hijye ga qk ek code modify krne k lye usko smjna zrori h
It provides following features

 Data hiding
 Simplicity: => less parameters passing
 Modularity
 Modifiability:
 Extensibility
 Maintainability
 Re-usability

Difference between access specifiers and access


modifiers(defining access level)
In java:
Access Specifier: - This can be understood as the access you provide
to your code in Java whether other classes can access your code or not.
E.g. public, private, protected and default.
Access Modifier: - Java provides both Access Specifier and Access
Modifiers for creating access to your Java code for other classes. Here
modifier is also used to do the same task but there are limitations.

1. Class Modifier:
oabstract :- This defines the restriction such that objects cannot
be created.
o final:- This restricts a class from being inherited.
o strictfp:- it is related to the checking of floating point values
irrespective of OS.
2. Variable Modifier:
o static: no object creation required
o final: cannot be reassigned
o transient: it is not serialized
o volatile: the values are liable for change

In cpp:
Access modifiers are used to implement an important aspect of Object-
Oriented Programming known as Data Hiding. Access Modifiers or Access
Specifiers in a class are used to assign the accessibility to the class
members. That is, it sets some restrictions on the class members not to get
directly accessed by the outside functions that’s why setters/getters are
used.
There are 3 types of access modifiers available in C++:
1. Public
2. Private
3. Protected

Data hiding

Data hiding is a software development technique specifically


used in object-oriented programming (OOP) to hide
data members. Data hiding ensures exclusive data access
to class members and protects object integrity by preventing
unintended or intended changes. The isolation of the data from the
direct access by the program is called data hiding or information hiding. For
implementing data hiding, encapsulation is used where data and function of a class
is protected from unauthorized access. In contrast, when the data and function is
encased into a single unit is known as encapsulation. Hence, the data hiding assists in
achieving the encapsulation. The functional details of an object can be handled
through access specifiers.
Key Differences between Abstraction and Data hiding

1. Abstraction shows the relevant information and rejects the non-essential details.
On the other hand, data hiding is used to hide the data from the parts of the
program.
2. The prior purpose of abstraction is to hide the complex implementation detail of
the program or software. On the contrary, data hiding is implemented to attain
encapsulation.
3. Abstraction is used in class to create a new user-defined datatype. As against, in
classes data hiding is used to make the data private.
4. The abstraction concentrates on the observable behavior of the data whereas data
hiding restricts or allow the use of data within a capsule.

What are the four Pillars/ Principles of OOP? :-)


 Encapsulation
 Abstraction
 Inheritance
 Polymorphism

Encapsulation:-
Encapsulation is an Object Oriented Programming concept that binds together the data and
functions that manipulate the data, and that keeps both safe from outside interference and
misuse.

Encapsulation is defined as the wrapping up of data under a single unit.it is a


protective shield that prevents the data from being accessed by the code
outside this shield.

Why Encapsulation?
 It is considered good practice to declare your class attributes as private
(as often as you can). Encapsulation ensures better control of your data,
because you (or others) can change one part of the code without affecting
other parts
 Increased security of data

Real life example:


Car example, only people with keys can unlock the car and drive it.
A car is having multiple parts..like steering,wheels,engine...etc..which binds together to form a single
object that is car. So, Here multiple parts of cars encapsulates itself together to form a single object that
is Car.

Abstraction
Abstraction means displaying only essential information and hiding the details. Data abstraction
refers to providing only essential information about the data to the outside world, hiding the
background details or implementation.
Real life Example:
DVD Player

Abstraction using Classes: We can implement Abstraction in C++ using


classes. Class helps us to group data members and member functions using
available access specifiers. A Class can decide which data member will be
visible to outside world and which is not.
Abstraction in Header files: One more type of abstraction in C++ can be
header files. For example, consider the pow() method present in math.h header
file. Whenever we need to calculate power of a number, we simply call the
function pow() present in the math.h header file and pass the numbers as
arguments without knowing the underlying algorithm according to which the
function is actually calculating power of numbers.
Abstraction using Classes
A Class can decide which data member will be visible to outside world and which is not using
access specifiers

Polymorphism in C++
Advantage: Helps us to avoid multiple if/else statements or switch cases.

Jb aik hi command sunne p diff behavior show kre

Polymorphism means "many forms". C++ polymorphism means that a call to a member
function will cause a different function to be executed depending on the type of object that
invokes the function. The ability of a message to be displayed in more than one form.

Real life example of polymorphism:


1. A person at the same time can have different characteristic. Like a man at the same time
is a father, a husband, an employee. So the same person posses different behavior in
different situations.

2. In real life example , polymorphism ye h k chand ek provided conditions h start m jinko


ap shru m provide krty ho r ap ek hi kam kehty ho lkn apki shru m jo provided conditions
thi unki base p wo ek hi kaam differently perform hga e.g give example of interview as a
SE and QA and in future u say to do work(); then us case m kia hga k SE vla SE vla
work perform kre ga r QA vla QA vla work perform kre ga

In C++ polymorphism is mainly divided into two types:


 Compile time Polymorphism
 Runtime Polymorphism

Compile time polymorphism:


 It is also called as static polymorphism, false polymorphism, early binding.
 When call to functions is resolved at compile time it is called compile time
polymorphism.
 In c++, Compile time polymorphism is achieved by using function overloading
and operator overloading.

Function Overloading:

When there are multiple functions with same name but different parameters then these
functions are said to be overloaded. Functions can be overloaded by change in number of
arguments or/and change in type of arguments

Overloading Considerations
TABLE 1

Function Declaration Element Used for Overloading?

Function return type No

Number of arguments Yes

Type of arguments Yes

Presence or absence of ellipsis Yes

Use of typedef names No

Unspecified array bounds No

const or volatile Yes, when applied to entire function

Ref-qualifiers Yes

Operator Overloading:

1. Operator overloading allows you to redefine the way operator works for user-
defined types only (objects, structures). It cannot be used for built-in types (int,
float, char etc.).
2. Two operators = and & are already overloaded by default in C++. For example: To
copy objects of same class, you can directly use = operator. You do not need to
create an operator function.

3. Operator overloading cannot change the precedence and associatively of


operators. However, if you want to change the order of evaluation, parenthesis
should be used.

4. There are 4 operators that cannot be overloaded in C++. They are :: (scope
resolution), . (member selection), .* (member selection through pointer to
function) and ?: (ternary operator)

Class Box{

Box operator+(const Box& b) {


Box box;
box.length = this->length + b.length;
return box;
}
Int main(){
// Add two object as follows:
Box3 = Box1 + Box2
}

Example 2:-
ostream& operator << (ostream &out, Time &tm)
{
out << "Time is: " << tm.hr << " hour : " << tm.min << " min : " << tm.sec << "
sec";
return out;
}

Runtime polymorphism:-

 It is also called as dynamic polymorphism, true polymorphism or late binding.


 When call to the function resolved at run time, it is called run time
polymorphism.
 In c++, run time polymorphism is achieved by using function overriding

Function overriding on the other hand occurs when a derived class has a definition for
one of the member functions of the base class. That base function is said to
be overridden .Function signature is exact same and also the return type.
The idea is that virtual functions are called according to the type of the object instance pointed
to or referenced, not according to the type of the pointer or reference. (mtlb point kis obj ko kr
rhy)
Function overriding is only done in derived classes.

It is like creating a new version of an old function, in the child class.

Function Hiding:-
Basically, a derived class with a function that has the same name as a base
class function doesn't actually overload the base class function - it completely hides it

class Base
{
public:
int fun()
{
cout<<"Base::fun() called";
}
int fun(int i)
{
cout<<"Base::fun(int i) called";
}
};

class Derived: public Base


{
public:
int fun() // Now this
single function has hided both
of the base class’s functions
{
cout<<"Derived::fun() called";
}
};

Difference between function overloading and overriding


Function overloading:
Same signature functions cannot exist in same scope e.g.
Void foo (); and double foo (); cannot exist in same scope.

Main Differences
1. Inheritance: Overriding of functions occurs when one class is inherited
from another class. Overloading can occur without inheritance.
2. Function Signature: Overloaded functions must differ in function
signature i.e. either number of parameters or type of parameters should
differ. In overriding, function signatures must be same.
3. Scope of functions: Overridden functions are in different scopes;
whereas overloaded functions are in same scope.
4. Behavior of functions: Overriding is needed when derived class function
has to do some added or different job than the base class function.
Overloading is used to have same name functions which behave
differently depending upon parameters passed to them.

What are manipulators?


Manipulators are the functions which can be used in conjunction with the insertion (<<)
and extraction (>>) operators on an object. Examples are endl and setw.

Inheritance in C++ (“is-A” relationship)


Such a mechanism that allows to eliminate redundant code

Ek esa feature jb hum ksi b class k existing code ko reuse krskein without coding it again.

The capability of a class to derive all the properties and characteristics from another
class instead of coding them again in the class which will cause code redundancy so
instead of that the derive class will inherit all the methods and properties from the base
class which is called Inheritance.
Real Life Example:
 TVs : https://thetechmoney.com/oop-concepts-with-real-word-examples/
 Cars: in interview prep video
 People
 Mobile Phones

Why And When To Use "Inheritance" and "Polymorphism"?


- It is useful for code reusability: reuse attributes and methods of an existing
class when you create a new class.
-When you want to provide specific implementation to an
inherited method.(for polymorphism)
 Advantages:
Application development time is less.

 Application take less memory.

 Application execution time is less.

 Application performance is enhance (improved).

 Redundancy (repetition) of the code is reduced or minimized so that we get


consistence results and less storage cost.

Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit
from more than one classes i.e. having more than one base classes.

Multiple inheritance not allowed in JAVA:

The Java programming language supports multiple inheritance of type, which is the
ability of a class to implement more than one interface.

The reason behind this is to prevent ambiguity. Consider a case where class B extends
class A and Class C and both class A and C have the same method display().
Now java compiler cannot decide, which display method it should inherit. To prevent
such situation, multiple inheritances is not allowed in java.

Real Life Example: Parents are a good example of multiple inheritance. Each child has
two parents—that’s just the way it is. So it makes sense that you can design classes by
using multiple inheritance. In some OO languages, such as C++, you can.

Multilevel Inheritance: In this type of inheritance, a derived class is created from


another derived class.
Real Life Example: Ek type k product k jb different versions nklty hain e.g. Different
models of same car.

Hierarchical Inheritance :-( Jb aik base class sa 1 sa zaada clases derive ki hui houn)
More than one derived class is created from a single base class.
Real Life Example: For example, a car is a common class from which
Audi, Ferrari, Maruti etc can be derived.

Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one
type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.
Abstract Class and Pure Virtual
Function in C++
Abstract Class is a class which contains at least one Pure Virtual function in it. Abstract classes
are used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must
provide definition to the pure virtual function, otherwise they will also become abstract class.
Real life Example:
 Animals have some common traits but we cannot give implementation of speak in the
base because each animal will have its own implementation of speak
 Think it like a fruit . If u go to any shop and ask for exactly for a fruit . The
shopkeeper will ask you for which fruit, he will suggest u mango , apple etc . But he
can't give u exactly the fruit . Because it does not exist , as it is an idea , a
classification. You can also compare with Animals , plants etc . This are all abstract
classes .Now in programming if u want instantiate the fruit class u can't . because it
won't be realistic . As it is an Abstract class . But u can instantiate the mango class ,
apple class as this are concrete class

Characteristics of Abstract Class.

1. Abstract class cannot be instantiated, but pointers and references of Abstract class type can be

created.

2. Abstract class can have normal functions and variables along with a pure virtual function.

3. Abstract classes are mainly used for Up-casting, so that its derived classes can use its interface.

4. Classes inheriting an Abstract Class must implement all pure virtual functions, or else they will

become Abstract too.

5. An abstract class can have constructors.

Abstract class in C++:-

 C++ ma hurr wou class jisme aik bhi pure virtual fuction hou use abstract class kehte

 C++ ma class k sath abstract ka keyword nai aata.


Comparison with Java in terms of Abstract Classes.
In Java, a class can be made abstract by using abstract keyword. Similarly a function can be

made pure virtual or abstract by using abstract keyword. In Java, we can have an abstract class

without any abstract method which means we still cannot instantiate such a class.

Interface (programming by contract):


Is m hum log chnd ek chezain declare kr dete h jis m hm kehty h k hum ne ek skeleton
provide krdia h ek tarah se ek contract ho rha hta h jis m hm methods ki prototype de
dete h ab kal ko apne apna kam krna h tu apko meri ye sari chezain implement krni
prein gi otherwise ap kam ni krskty mtlb hm agly bnde ko inforce kr rhy ek tarah se k
mera kaam pehle pora kro phr apna kaam krskty ho wrna ni chle ga apka kam b(totally
looks like a contract)
Real life example: Punjab college branches – uniform – accept it otherwise no
admission.

An interface does not have implementation of any of its methods, it can be considered as a
collection of method declarations. In C++, an interface can be simulated by making all
methods as pure virtual. In Java, there is a separate keyword for interface.

Difference between interface and abstract class:


In interface all funs are pure virtual whereas in abstract classes there can be at least 1
pure virtual function.
Diiference in Abstract (pure virtual ) and virtual functions:-

Virtual Function Abstract(Pure virtual)

Virtual function has their definition in the class. Pure virtual function has no definition.

Declaration: virtual funct_name (parameter_list) Declaration: virtual funct_name(parameter_list)=0;


{. . . . .};

It has no concept of derived class. If a class contains at least one pure virtual function,
then it is declared abstract.

If required, the derived class can override a virtual In case of pure virtual function derived class has to
Virtual Function Abstract(Pure virtual)

function. definitely override the pure virtual function.

virtual void s() //virtual function virtual void s() = 0; // Pure


{ Virtual Function

cout<<" In Base \n";

Its obj can be created


Its obj cant be created

Final Keyword

Final variables
Difference in Final and Normal Variable.
The only difference between a normal variable and a final variable is that we can re-assign
value to a normal variable but we cannot change the value of a final variable once assigned.

Final methods:-
When a method is declared with final keyword, it is called a final method. A final method cannot
be overridden.We must declare methods with final keyword for which we required to follow the
same implementation throughout all the derived classes.Ab derived clases is function ko
override krke new implementation nai da sakti
Final, Finally and Finalize
Final:-
Already told above

Finally keyword
The finally block will be executed after the try and catch blocks, but before control transfers back
to its origin ,finally keyword guarantees that a section of code will be executed, even if an
exception is thrown

Application of finally block: So basically the use of finally block is resource


deallocation. Means all the resources such as Network Connections, Database
Connections, which we opened in try block are needed to be closed so that we
won’t lose our resources as opened. So those resources are needed to be
closed in finally block.
Note: The finally block is a key tool for preventing resource leaks. When closing
a file or otherwise recovering resources, place the code in a finally block to
ensure that resource is always recovered.

Finalize method
It is a method that the Garbage Collector always calls just before the
deletion/destroying the object which is eligible for Garbage Collection, so as to
perform clean-up activity. Clean-up activity means closing the resources
associated with that object like Database Connection, Network Connection or
we can say resource de-allocation. Remember it is not a reserved keyword.

Disadvantages of Inheritance:-
1. One of the main disadvantages of inheritance is the increased time/effort it takes the program to
jump through all the levels of overloaded classes. If a given class has ten levels of abstraction
above it, then it will essentially take ten jumps to run through a function defined in each of
those classes
2. Main disadvantage of using inheritance is that the two classes (base and inherited class) get
tightly coupled. This means one cannot be used independent of each other.
3. Also with time, during maintenance adding new features both base as well as derived classes are
required to be changed. If a method signature is changed then we will be affected in both
cases (inheritance & composition)

Further Notes
Disadvantages:-
 Inherited functions work slower than normal function as
there is indirection.
 Improper use of inheritance may lead to wrong solutions.
 Often, data members in the base class are left unused
which may lead to memory wastage.
 Inheritance increases the coupling between base class
and derived class. A change in base class will affect all
the child classes.

Advantages:

 Inheritance promotes reusability. When a class inherits or


derives another class, it can access all the functionality
of inherited class.
 Reusability enhanced reliability. The base class code will
be already tested and debugged.
 As the existing code is reused, it leads to less
development and maintenance costs.
 Inheritance makes the sub classes follow a standard
interface.
 Inheritance helps to reduce code redundancy and
supports code extensibility.
 Inheritance facilitates creation of class libraries.

Languages that supports Multiple Inheritance:-


C++, Scala ( in Traits ), OCaml, Perl 6, Python

The diamond problem :


The diamond problem occurs when two superclasses of a class have a common base
class. For example, in the following diagram, the TA class gets two copies
of all attributes of Person class, this causes ambiguities.

Diagram of diamond inheritance, a

Problem that virtual inheritance is trying to


solve
Solution Of Diamond Problem:-
The solution to this problem is ‘virtual’ keyword. We make the classes ‘Faculty’ and ‘Student’ as
virtual base classes to avoid two copies of ‘Person’ in ‘TA’ class.

class Person {};

class Faculty : virtual public Person {};

class Student : virtual public Person {};

class TA : public Faculty, public Student {}


Virtual Inheritance:-
Virtual inheritance is a C++ technique that ensures only one copy of a base class's member that
are inherited by grandchild derived classes. Other wise can also cause Diamond problem.

-:Difference between Structs and Clases:-


Struct:-
 Struct is pass-by-copy
 struct members are public by default.
 Structures can not be garbage collected so no efficient memory
management.
 Sizeof empty structure is 0 Bytes

Class:-
 Class is pass-by-reference
 A class has all members private by default.
 Classes allow to perform cleanup (garbage collector) before object
is deallocated because garbage collector works on heap memory
 Sizeof empty class is 1 Byte

When deriving a struct from a class/struct, default access-specifier for a base


class/struct is public. And when deriving a class, default access specifier is
private.

When struct can be created on heap:-


When a struct is boxed means jb hm aik struct k object ko class k andr as a datamember rakh
lain ge aur ab jb hm class ka object banaien ge to wou heap pr bane ga
Association
Association is nothing but a relationship b/w 2 classes and it has 2 types i.e. composition & aggregation.

Ek esa relationship h jis m 2 objects krty tu independently exist h ek dusry se lkn unhe waqti tor
p interaction krna pr jta h tu wo kam pora krty h aur bd m phr separate ho jte mtlb hm ese b
keh skty k waqti tor p associate krty h ek dusry se

Real life example:


Relationship b/w interviewer and candidate.
is a relationship where all object have their own lifecycle and there is no owner.
Let’s take an example of Teacher and Student. Multiple students can associate
with single teacher and single student can associate with multiple teachers but
there is no ownership between the objects and both have their own lifecycle.
Both can create and delete independently.

Aggregation(esa relationship js m ek chez k khtm krnse se dusri chez khtm


ni hgi)

is a specialize form of Association where all object have their own lifecycle but
there is ownership and child object can not belong to another parent object.
Let’s take an example of Department and teacher. A single teacher can not
belongs to multiple departments, but if we delete the department teacher object
will not destroy.

class Address { };
class Employee
{
Address* address;
Employee(Address* address)
{
this->address = address;
}
E.g. example of Principal and school

Note
Agr ma yahan new address () krke bana bhi laita pr destructor ma usko delete nai krta
aur mere pass agr garbage collector bhi nai ha tou tb bhi ye aggregation hoogi wrna
wou composition bn jaye gi

Composition: - (“has a”+ “whole-part”) e,g ek chez ksi dusri chez se mil k bni ho
Is again specialize form of Aggregation and we can call this as a “death”
relationship. It is a strong type of Aggregation. Child object does not have their
lifecycle and if parent object deletes all child object will also be deleted.

Example:
1. Interview room: (Room has bricks) Suppose abi hm jis
kamray m bethy huay is kamray ki devarein eento ki vja se
bne hui hain kamray ko khtm krne k lye ye devarein torni
prein gi jisse entein b yahan se khtm ho jaen gi tu ye entein
aur devarein hain na ye is kamray k lye composition ka role
play kr rhein hain qk karma tb hi hai jb ye devarein wegara
hain.

2. Let’s take again an example of relationship between House and


rooms. House can contain multiple rooms there is no independent
life of room and any room can not belongs to two different house if
we delete the house room will automatically delete.

3. Let’s take another example relationship between Questions and


options. Single questions can have multiple options and option can
not belong to multiple questions. If we delete questions options will
automatically delete

class Time{ };

class Date{};

class Event
{
Time eventTime; \\ Yahan objects hi rukh liye dosre class k
Date eventDay;
};

Constructor chaining:
If a subclass constructor invokes a constructor of its superclass, either explicitly
or implicitly, you might think that a whole chain of constructors called, all the
way back to the constructor of Object. This, in fact, is the case. It is
called constructor chaining.

Java | static classes:


Can a class be static in Java?
The answer is Yes, some classes can be made static in Java. Java
supports Static Instance Variables , Static Methods, Static Block and Static
Classes
Java allows a class to be defined within another class. These are called Nested
Classes. The class in which the nested class is defined is known as the Outer
Class. Unlike top level classes, Inner classes can be Static. Non-static nested
classes are also known as Inner classes.
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.

What are the differences between static and non-static nested classes?
The following are major differences between static nested classes and inner
classes.
1. A static nested class may be instantiated without instantiating its outer class.
2. Inner classes can access both static and non-static members of the outer
class. A static class can access only the static members of the outer class.

Why static variables need to be avoided?


First of all static variables are global in terms of their lifecycle they remain in memory till
the end of the main program secondly all objects share the same copy of the variable
which makes it difficult to trace the changes made in the variable as all objects share the
same copy and also makes it difficult to debug because programming convention is ‘The
smaller the scope of a variable the more convenient it is to use’ that’s why when we
OOP approach it is preferable to make most of the details private not public moreover
they are similar to global variables and in programming the usage of global variables is
totally not recommended. They are often misused and that can lead to code that is rather
unpleasant to work with. However, static variables are often misuse and as they introduce
global state to the app, they make debugging much harder

They are not part of object body and hence doesn't reflect a true object oriented design
component.

1. Since static variable are class member, all threads tries to access them has to be
manage.
2. If one thread change value of a static variable that can possibly break functionality
of other threads.
 Impossible to secure
 Impossible to encapsulate
 Impossible to virtualize
 Impossible to override
Example:
When to use static variables and methods?
use static variables when : The value of the variable is independent of the objects (not
unique for each object). E.g. number of students or name of school or college if there is
such a situation in which we want to use a variable that preserves its value during each
function call.
When you need something that will be used through out the application and every instance
need to know the variable
static variables are often used for constants, which is common to all the instances if the
class. For example, many people don't like to "hard-code" constants in their code.

Difference between static class and singleton pattern?


The big difference between a singleton and a bunch of static methods is that singletons can
implement interfaces (or derive from useful base classes, although that's less common, in
my experience)
A singleton allows access to a single created instance A static class allows only static
methods with no instance
A static class in Java has only static methods. It is a container of functions.

Singleton class is a pattern in Object Oriented Design. A Singleton class has only one
instance of an object in JVM.

C# | Static Class
In C#, a static class is created by using static keyword. A static class can only contain
static data members, static methods, and a static constructor. It is not allowed to create
objects of the static class. Static classes are sealed, means you cannot inherit a
static class from another class.

There is no "static class" in C++. The nearest concept would be a class with
only static methods.
JAVA:
The answer is YES, we can have static class in java.
In java, we have static instance variables as well as static methods and
also static block. Classes can also be made static in Java but no static local variables
are made in Java.

Static Function:-
 Static method, the method can only access only static data members and static
methods of another class or same class but cannot access non-static methods and
variables.
 In static method, the method use compile time or early binding. For this reason we can
access static method without creation a instance
 In static method, we cannot override a static method, because of early binding.

 A static member function cannot have access to the this pointer of


the class because they are not obj specific.

Static Data Member:-


A static data member is shared among all instances of the class. ... 2) Any static
variable is initialized before any objects is created. That's why compiler don't allow to
define static variable inside constructor as constructor will be called when a object is
created.
In cpp context: we can’t define a static variable inside the class as well as inside the constructor
but we can declare them. To define them it would be done outside the class.

Note:-
If to initialize the static data member by your own value then it should be done outside class
using following syntax

class GfG
{
public:
static int i;
};

int GfG::i = 1;

OR ELSE
If it s not initialized then it would be initialized with zero by the compiler.

Static Variables in a Function :-( only initialized once)


When a variable is declared as static, space for it gets allocated for the lifetime of the
program. Even if the function is called multiple times, space for the static variable is allocated
only once and the value of variable in the previous call gets carried through the next function
call.
void demo()
{

static int count = 0;


count++;
}
int main()
{
for (int i=0; i<5; i++)
demo();
return 0;
}
Output:
0 1 2 3 4

Important Note:-
 A Static function can access only static data members and Static member functions.
 A Non-Static Function can access both A static and non static data member and
member Functions

Static Object:-

 Persistence: it remains in memory until the end of the program.


 Visibility: if it is defined within a function/block, its scope is limited to the
function/block. It cannot be accessed outside of the function/block
 C++ supports both local static object and global static object
 Static object can call non-Static data members and Non-Static member functions.
 Static object ab apne scope pr nai aur kisi local scope k hisab sa nai blke jb
bhi poora program khtam hooga aur main () hoone lage ga tb destruct hooga
mtlb End of the program tk zinda rehta ha ye.
How about local static objects?

class Test
{
public:
Test()
~Test()

};
void myfunc()
{
static Test obj;
} // Object obj is still not destroyed because it is static

int main()
{
myfunc(); // Destructor will not be called here
std::cout << "main () terminates\n";
return 0; }

Output:-
Constructor is executed
main() terminates
Destructor is executed

How about global static objects? (Hur global cheez main ma enter hoone
sa pehle create hooti).

class Test
{
a = 10;
public:
Test()
~Test()

};
static Test obj;

int main()
{
std::cout << "main() starts\n";
std::cout << obj.a;
std::cout << "\nmain() terminates\n";
return 0;
}

Output:
Constructor is executed
main() starts
10
main() terminates
Destructor is executed

Static functions in C:
In C, functions are global by default. The “static” keyword before a function
name makes it static. For example, below function fun () is static.
static int fun(void)

printf("I am a static function ");

Unlike global functions in C, access to static functions is restricted to the file


where they are declared. Therefore, when we want to restrict access to
functions, we make them static. Another reason for making functions static can
be reuse of the same function name in other files.

Inline Functions in cpp:


Read this: https://www.geeksforgeeks.org/inline-functions-cpp/

Static blocks in Java


Unlike C++, Java supports a special block, called static block (also called static
clause) which can be used for static initializations of a class. This code inside
static block is executed only once: the first time the class is loaded into
memory. Also, static blocks are executed before constructors.

The Initializer Block in Java


Initializer block contains the code that is always executed whenever an instance
is created. It is used to declare/initialize the common part of various
constructors of a class. We can note that the contents of initializer block are
executed whenever any constructor is invoked (before the constructor’s
contents)
Difference between value type and reference type:
A Value Type holds the data within its own memory allocation and a Reference Type contains
a pointer to another memory location that holds the real data. Reference Type variables are
stored in the heap while Value Type variables are stored in the stack.

Difference between deep copy and shallow copy:


Shallow Copy: Creating a new object and then copying the value type fields of
the current object to the new object. But when the data is reference type, then
the only reference is copied but not the referred object itself. Therefore the
original and clone refer to the same object.
Deep Copy: It is a process of creating a new object and then copying the fields
of the current object to the newly created object to make a complete copy of the
internal reference types. If the specified field is a value type, then a bit-by-bit
copy of the field will be performed. If the specified field is a reference type, then
a new copy of the referred object is performed.

You might also like