OOP Relatedquestions
OOP Relatedquestions
Java, C++, C#, Python, PHP, Ruby, Perl, Dart, Swift, Scala and Smalltalk.[1]
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.
Data hiding
Simplicity: => less parameters passing
Modularity
Modifiability:
Extensibility
Maintainability
Re-usability
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
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.
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.
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
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
Polymorphism in C++
Advantage: Helps us to avoid multiple if/else statements or switch cases.
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.
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
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.
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{
Example 2:-
ostream& operator << (ostream &out, Time &tm)
{
out << "Time is: " << tm.hr << " hour : " << tm.min << " min : " << tm.sec << "
sec";
return out;
}
Runtime polymorphism:-
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.
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";
}
};
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.
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
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.
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.
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
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
C++ ma hurr wou class jisme aik bhi pure virtual fuction hou use abstract class kehte
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.
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.
Virtual function has their definition in the class. Pure virtual function has no definition.
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)
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
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:
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
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
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.
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.
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.
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.
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.
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.
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:-
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)