Oops Notes
Oops Notes
● P rocedural Programming Paradigm- specifies the stepsa program must take to reach
the desired state, usually read in order from top to bottom.
● Object-Oriented Programming or OOP- organizes programsas objects, that contain
some data and have some behavior.
● Parallel Programming- breaks a task into subtasksand focuses on executing them
simultaneously at the same time.
● L ogical Programming Paradigm- based on formal logic,which refers to a set of
sentences expressing facts and rules about how to solve a problem
● Functional Programming Paradigm- programs are constructedby applying and
composing functions.
● Database Programming Paradigm- used to manage dataand information structured as
fields, records, and files.
5. Can we run a Java application without implementing the OOPs concept?
owever, on the other hand, C++ can be implemented without OOPs, as it also
H
supports the C-like structural programming model.
.
1 elpful in solving very complex level of problems.
H
2. Highly complex programs can be created, handled, and maintained easily using
object-oriented programming.
.
3 It promote code reuse, thereby reducing redundancy.
4. It also helps to hide the unnecessary details with the help of Data
Abstraction.
5. OOPs, are based on a bottom-up approach, unlike the Structural programming
paradigm, which uses a top-down approach.
.
6 Polymorphism offers a lot of flexibility in OOPs.
7. With OOPs, the readability and understandability of the code increase multifold.
8. It provides the feature of data hiding that is good for security concerns.
9. We can provide the solution to real-world problems if we are using object-oriented
programming.
he programming language is called pure object-oriented language that treats everything inside
T
the program as an object. The primitive types are not supported by the pure OOPs language.
ava is not an entirely pure object-oriented programming language. The following are the
J
reasons:
● J ava supports and uses primitive data types such as int, float, double, char, etc. These
data types in Java are not treated as objects.
● Primitive data types are stored as variables or on the stack instead of the heap.
● In Java, static methods can access static variables without using an object, contrary to
object-oriented concepts.
class is an entity that determines how an object will behave and what the object will contain.
A
In other words, it is a blueprint or a set of instruction to build a specific type of object. It provides
initial values for member variables and member functions or methods.
So when an object is created, it automatically takes the data and functions that are defined in
the class.
Therefore the class is basically a template or blueprint for objects.
bjects are instances of a class created with specifically defined data. Objects can correspond
O
to real-world objects or an abstract entity.So theobjects consume space and have some
characteristic behavior.
For example, a specific car.
lasses do not consume any memory. They are just a blueprint based on which
C
objects are created. Now when objects are created, they actually initialize the class
members and methods and therefore consume memory. And the size of instance is equal to the
sum of the size of members define in class.
es, you are allowed to call the base class without instantiating it but there are some conditions
Y
that are applicable.
•If it is a static method
•The base class is inherited by some other subclass
int Student::getMarks()
{
return
marks;
}
parameter is a variable used during the declaration of the function or subroutine, and
A
arguments are passed to the function body, and it should match with the parameter defined.
etters are those functions that allow us to access data members of the object. However, these
G
functions do not change the value of data members. These are also called accessor functions.
etters are the member functions that allow us to change the data members of an object. These
S
are also called mutator functions.
Instance Variable:It is an object-level variable.It should be declared inside a class but must be
outside a method, block, and constructor. It is created when an object is created by using the
new keyword. It can be accessed directly by calling the variable name inside the class.
Static Variable: It is a class-level variable. Itis declared with keyword static inside a class but
must be outside of the method, block, and constructor. It stores in static memory. Its visibility is
the same as the instance variable. The default value of a static variable is the same as the
instance variable. It can be accessed by calling the class_name.variable_name.
Local Variable:It is a method-level variable. Itcan be declared in method, constructor, or block.
Note that the use of an access modifier is not allowed with local variables. It is visible only to the
ethod, block, and constructor in which it is declared. Internally, it is implemented at the stack
m
level. It must be declared and initialized before use.
Reference Variable:It is a variable that points toan object of the class. It points to the location
of the object that is stored in the memory.
● Inheritance
● Encapsulation
● Polymorphism
● Data Abstraction
ncapsulation is the process of binding data members and methods of a program together to do
E
a specific job, without revealing unnecessary details.
ccess modifiers determine the scope of the method or variables that can be accessed from
A
other various objects or classes.. These access specifiers also play a very vital role in achieving
Encapsulation. There are four types of access modifiers, and they are as follows:
● Private
● Protected
● Public
● Default (only in java)
( For C++)
i) Public: All the class members with public modifier can be accessed from anywhere(inside and
outside the class).
ii) Private: All the class members with private modifier can only be accessed by the member
function inside the class.
iii) Protected: This access modifier is similar to private access modifier, i.e., it can’t be accessed
outside of its class unless, with the help of friend class, the difference is that the class members
declared as Protected can be accessed by any subclass(derived class) of that class as well.
ote:If we do not specify any access modifiers forthe members inside the class, then by
N
default, the access modifier for the members will be Private.
(For Java)
ote:If we do not specify any access modifiers forthe members inside the class, then by
N
default, the access modifier for the members will be Default (or package-private).
ealed modifiers are the access modifiers where the methods can not inherit it. Sealed
S
modifiers can also be applied to properties, events, and methods. This modifier cannot be used
to static members.
he term “inheritance” means “receiving some quality or behavior from a parent to
T
an offspring.” In object-oriented programming, inheritance is the capability of a class to derive
properties and characteristics from another class. Inheritance can also be defined as the Is-A
relationship, which is also known as the parent-child relationship.
Advantages:
● C ode reusability: We can reuse the code when we inherit the existing class’s methods
and fields into a new class.
● The runtime polymorphism (method overriding) can be achieved by inheritance only.
Modes of Inheritance:
. P
1 ublic mode
2. Protected mode
3. Private mode
The base class is the root class- the most generalized class.
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.
yntax:
S
object.class_name::method_name();
he Person class constructor is called twice: once when the Father class object is created and
T
next when the Mother class object is created. The properties of the Person class are inherited
twice, giving rise to ambiguity.
Since the Person class constructor is called twice, the destructor will also be called twice when
the Child class object is destructed.
he solution to the diamond problem is to use thevirtualkeyword. We make the two parent
T
classes (who inherit from the same grandparent class) into virtual classes in order to avoid two
copies of the grandparent class in the child class.
e will use the virtual keyword when classes Father and Mother inherit the Person class. This is
W
usually called “virtual inheritance," which guarantees that only a single instance of the inherited
class (in this case, the Person class) is passed on.
In other words, the Child class will have a single instance of the Person class, shared by both
the Father and Mother classes. By having a single instance of the Person class, the ambiguity is
resolved.
ne thing to note about virtual inheritance is that even if the parameterized constructor of the
O
Person class is explicitly called by Father and Mother class constructors through initialization
lists, only the base constructor of the Person class will be called.
This is because there's only a single instance of a virtual base class that's shared by multiple
classes that inherit from it.
To prevent the base constructor from running multiple times, the constructor for a virtual base
class is not called by the class inheriting from it. Instead, the constructor is called by the
constructor of the concrete class.
hat if you need to execute the parameterized constructor of the base class? You can do so by
W
explicitly calling it in the Child class rather than the Father or Mother classes.
ata abstraction refers to providing only necessary information about the outside world’s data,
D
hiding the background details or implementation.
For example, consider a car. You only need to know how to run a car, and not how the
wires are connected inside it. This is obtained using Abstraction.
Advantages Of Abstraction
O
● nly you can make changes to your data or function, and no one else can.
● It makes the application secure by not allowing anyone else to see the background
details.
● Increases the reusability of the code.
● Avoids duplication of your code.
ata abstraction is accomplished with the help of abstract methods or abstract classes or
D
interfaces.
hese methods are basically declared but not defined and If these methods need to be used
T
later in some subclass that time those methods have to be exclusively defined in the subclass.
34. What is an abstract class?
n abstract class is a special class containing abstract methods. The significance of
A
abstract class is that the abstract methods inside it are and only declared and not implemented.
So as a result, when a subclass inherits the abstract class and needs to use
its abstract methods, they need to define and implement them.
● Instantiation of an abstract class is not allowed. It must be inherited.
● An abstract class can have both abstract and non-abstract methods.
● An abstract class (in java) must have at least one abstract method.
● An abstract class (in C++) has at least one pure virtual function (i.e., a function that has
no definition).
● It is always public.
● It is declared using the keyword abstract
● It can have constructors and static methods also.
● It can have final methods which will force the subclass not to change the body of the
method.
● The purpose of an abstract class is to provide a common definition of the base class that
multiple derived classes can share.
n interface refers to a special type of class, which contains methods, but not their
A
definition. Only the declaration of methods is allowed inside an interface. To use an
interface, you cannot create objects. Instead, you need to implement that interface
and define the methods for their implementation.
An interface is a collection of an abstract method. If the class implements an interface, it thereby
inherits all the abstract methods of an interface.There are mainly three reasons to use interfaces
in Java. They are given below.
● It is used to achieve abstraction.
● By interface, we can support the functionality of multiple inheritance.
● It can be used to achieve loose coupling.
he C++ interfaces are implemented using abstract classes, and these abstract classes should
T
not be confused with data abstraction, which is a concept of keeping implementation details
separate from associated data.
A class is made abstract by declaring at least one of its functions as a pure virtual function. A
pure virtual function is specified by placing "= 0" in its declaration.
Example: The following function is a pure virtual function.
virtual void fun() = 0;
36. How is an abstract class different from an interface?
he main difference between the two is that, when an interface is implemented, the subclass
T
must define all its methods and provide its implementation. Whereas when an abstract class is
inherited, the subclass does not need to provide the definition of its abstract method, until and
unless the subclass is using it.
ero instances will be created for an abstract class. In other words, you cannot create an
Z
instance of an Abstract Class.You first need to create a subclass that implements all the
methods before an object can be initialized.
38. Difference between extends and implements.
omposition describes a class that references one or more objects of other classes in instance
C
variables. This allows you to model a has-a association between objects.
The main benefits of composition are:
● Reuse existing code
● Design clean APIs
● Change the implementation of a class used in a composition without adapting any
external clients.
olymorphism is composed of two words - “poly” which means “many”, and “morph”
P
which means “shapes”. Therefore Polymorphism refers to something that has many
Shapes.
In OOPs, Polymorphism refers to the process by which some code, data, method, or
object behaves differently under different circumstances or contexts.
Compile-time polymorphismandRun time polymorphismare the two types of
polymorphisms in OOPs languages.
41. What is compile time polymorphism?
ompile time polymorphism, also known as Static Polymorphism, refers to the type of
C
Polymorphism that happens at compile time.
What it means is that the compiler decides what shape or value has to be taken by
the entity in the picture.It can be achieved through Method overloading or operator overloading.
C++ supports compile-time polymorphism with the help of features like templates, function
#
overloading, and default arguments.
untime polymorphism, also known as Dynamic Polymorphism, refers to the type of
R
Polymorphism that happens at the run time. What it means is it can't be decided by the
compiler. Therefore what shape or value has to be taken depends upon the execution. Hence
the name Runtime Polymorphism.It can be achieved with the help of method overriding.
● Method overriding:Overriding is a runtime polymorphismfeature in which an entity has
the same name, but its implementation changes during execution. It is a feature that
allows you to redefine the parent class method in the child class based on its
requirement. In other words, whatever methods the parent class has by default are
available in the child class. But, sometimes, a child class may not be satisfied with
parent class method implementation. The child class is allowed to redefine that method
based on its requirement. This process is called method overriding.
C++ supports Runtime polymorphism with the help of features like virtual functions. Virtual
#
functions take the shape of the functions based on the type of object in reference and are
resolved at runtime.
perator overloading is not supported by Java as, It makes the interpreter put more effort to
O
understand the actual functionality of the operator making code complex and difficult to
compile.Operator overloading makes programs more error-prone.However, the feature of
operator overloading can be achieved in method overloading in a simple, clear, and error-free
way.
es, we can also overload the main() method in Java. Any number of main() methods can be
Y
defined in the class, but the method signature must be different.
6. What is a constructor?
4
A constructor is a special type of member function that is called automatically when an object is
created. The constructors serve the special purpose of initializing the objects.
● A constructor has the same name as the class itself.
● Constructors don’t have a return type, not even void.
● If we do not specify a constructor, the C++ compiler generates a default constructor for
us (expects no parameters and has an empty body).
● It cannot be marked as static.
● It cannot be marked as abstract or virtual.
● It cannot be overridden.
● It cannot be final.
● They are public.
● You cannot refer to their address
● They cannot be inherited though derived class can call the base class constructor
ypes of Constructors
T
There are three types of constructors in C++ they are:
) D
1 efault constructor
2) Parameterized Constructor
3) Copy Constructor
1. D
efault Constructor (No argument constructor)
The default constructor is the constructor that doesn’t take any argument. It has no
parameters.
he constructor overloading can be defined as the concept of having more than one constructor
T
with different parameters so that every constructor can perform a different task.With constructor
overloading, objects can be created in different ways. Various Collection classes in Java API are
examples of constructor overloading.
In OOPs, constructor chaining is a sequence of invoking constructors (of the same class) upon
initializing an object. It is used when we want to invoke a number of constructors, one after
another by using only an instance. In other words, if a class has more than one constructor
(overloaded) and one of them tries to invoke another constructor, this process is known as
constructor chaining. In C++, it is known as constructor delegation and it is present from C++ 11.
49. Is it possible for a class to inherit the constructor of its base class?
he copy constructor and the assignment operator (=) both are used to initialize one
T
object using another object.
If we pass by value in copy constructor, we will stuck in infinite loop. A call to the copy
constructor would be made to call the copy constructor which becomes a non-terminating chain
of calls. Thats why we should pass by reference.
52. Does C++ compiler create default constructor when we write our own?
o, the C++ compiler doesn’t create a default constructor when we initialize our own, the
N
compiler by default creates a default constructor for every class; But, if we define our own
constructor, the compiler doesn’t create the default constructor. This is so because the default
constructor does not take any argument and if two default constructors are created, it is difficult
for the compiler which default constructor should be called.
estructors are also special methods. But destructors free up the resources and
D
memory occupied by an object. Destructors are automatically called when an object
is being destroyed.
he destructor also recovers the heap space which was allocated to the destroyed object. It
T
also start closing the files and database connections of the object, etc.
Destructor rules
.
1 he name should begin with a tilde sign(~) and must match the class name.
T
2. There cannot be more than one destructor in a class.
3. Unlike constructors that can have parameters, destructors do not allow any parameter.
4. They do not have any return type, just like constructors.
5. When you do not specify any destructor in a class, the compiler generates a default
destructor and inserts it into your code.
ote:Destructor is called automatically for the objectformed by static allocation whereas you
N
have to call destructor manually for dynamic allocation.
Shallow Copy
n object is created by copying all of the member field values. Here, the pointer will be copied
A
but not the memory it points to. It means that the original object and the created copy will now
point to the same memory address, which is generally not preferred. Since both objects will
reference the same memory location, then changes made by one will reflect those changes in
another object. Since we wanted to create a replica of the object, this purpose will not be filled
by Shallow copy.
Note: The assignment operator and the default copy constructor make a shallow copy.
Deep Copy
n object is created by copying all the fields, and it also allocates similar memory resources with
A
the same value to the object. To perform Deep copy, we need to explicitly define the copy
constructor and assign dynamic memory as well if required. Also, it is necessary to allocate
memory to the other constructors’ variables dynamically.
55. What is an exception?
o one wants its software to fail or crash. Exceptions are the major reason for software failure.
N
Exceptions can be of any type – Runtime exception, Error exceptions. The exceptions can be
handled in the program beforehand and prevent the execution from stopping. This is known as
exception handling.
So exception handling is the mechanism for identifying the undesirable states that
the program can reach and specifying the desirable outcomes of such states.
Try-catch is the most common method used for handling exceptions in the program.
n error means a problem that the program should not catch while the exception implies a
A
condition that should be caught by the program.
try/ catch block helps to handle exceptions. The try block explains a set of statements that
A
may have an error. The catch block basically catches the exception.
arbage collection refers to this mechanism of handling the memory in the program.
G
Through garbage collection, the unwanted memory is freed up by removing the
objects that are no longer needed.
anipulators are the functions which can be used in conjunction with the insertion (<<) and
M
extraction (>>) operators on an object. Examples are endl and setw.
“ This” pointer holds the current object’s address; in simple words, this pointer points to the
class’s current object.
HIS keyword is used as a pointer which differentiates between the current object with the
T
global object. It refers to the current object When class attributes and parameterized
constructors both have the same name, this keyword is used. Keywords this invokes the current
class constructor, method of the current class, return the object of the current class, pass an
argument in the constructor, and method call.
token is the smallest element of a program that is meaningful to the compiler. Tokens can be
A
classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
The static keyword is a non-access modifier in Java that is applicable for the following:
1. Blocks
2. Variables
3. Methods
4. Classes
When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object.
Static data members belong to class. There is no need to create objects.
Static blocks
If you need to do the computation in order to initialize your static variables, you can declare a
static block that gets executed exactly once, when the class is first loaded.
Static variables
hen a variable is declared as static, then a single copy of the variable is created and shared
W
among all objects at the class level. Static variables are, essentially, global variables. All
instances of the class share the same static variable.
Important points for static variables:
● We can create static variables at the class level only.
● static block and static variables are executed in the order they are present in a program.
Static methods
hen a method is declared with the static keyword, it is known as the static method. The most
W
common example of a static method is the main( ) method. Any static member can be accessed
before any objects of its class are created, and without reference to any object. Methods
declared as static have several restrictions:
● They can only directly call other static methods.
● They can only directly access static data.
● They cannot refer to this or super in any way.
Static Classes
class can be made static only if it is a nested class. We cannot declare a top-level class with a
A
static modifier but can declarenested classesasstatic. Such types of classes are called Nested
static classes. Nested static class doesn’t need a reference of Outer class. In this case, a static
class cannot access non-static members of the Outer class.
False
inalize method helps to perform cleanup operations on the resources which are not currently
F
Used and also help to clean before Garbage Collection(GC). It performs memory management
tasks. Finalize method is protected, and it is accessible only through this class or by a derived
class.
67. What is a finally block?
finally block executes when the try block exits and It also executes even in case some
A
unexpected exception is encountered. Finally block normally consists of some important part of
the program.
Final Variables
hen a variable is declared with the final keyword, its value can’t be modified, essentially, a
W
constant. This also means that you must initialize a final variable. It always refers to the same
object by the property of non-transversity.
If the final variable is a reference, this means that the variable cannot be re-bound to reference
another object, but the internal state of the object pointed by that reference variable can be
changed i.e. you can add or remove elements from the final array or final collection.
ote- the difference between C++ const variablesand Java final variables. const variables in
N
C++ must be assigned a value when declared. For final variables in Java, it is not necessary as
we see in the above examples. A final variable can be assigned value later, but only once.
As we all know that a final variable cannot be re-assign. But in the case of a reference final
variable, the internal state of the object pointed by that reference variable can be changed. Note
that this is not re-assigning. This property of final is called non-transitivity.
The non-transitivity property also applies to arrays, because arrays are objects in Java. Arrays
with the final keyword are also called final arrays.
Final classes
hen a class is declared with final keyword, it is called a final class. A final class cannot be
W
extended(inherited).
There are two uses of a final class:
Usage 1: One is definitely to prevent inheritance, as final classes cannot be extended. For
example, all Wrapper Classes like Integer, float, etc. are final classes. We can not extend them.
Usage 2: The other use of final with classes is to create an immutable class like the predefined
String class. One can not make a class immutable without making it final.
Final Methods
hen a method is declared with final keyword, it is called a final method. A final method cannot
W
be overriden. TheObjectclass does this—a numberof its methods are final. We must declare
methods with the final keyword for which we are required to follow the same implementation
throughout all the derived classes.
69. What does const keyword do in c++?
henever const keyword is attached with any method(), variable, pointer variable, and with the
W
object of a class it prevents that specific object/method()/variable to modify its data items value.
Constant Variables:
There are a certain set of rules for the declaration and initialization of the constant variables:
● The const variable cannot be left un-initialized at the time of the assignment.
● It cannot be assigned value anywhere in the program.
● Explicit value needed to be provided to the constant variable at the time of declaration of
the constant variable.
ass const-argument value to a non-const parameter of a function cause error: Passing const
P
argument value to a non-const parameter of a function isn’t valid it gives you a compile-time
error.
Constant Objects:
ike member functions and member function arguments, the objects of a class can also be
L
declared as const. An object declared as const cannot be modified and hence, can invoke only
const member functions as these functions ensure not to modify the object.
Syntax:
const Class_Name Object_name;
● When a function is declared as const, it can be called on any type of object, const object
as well as non-const objects.
● Whenever an object is declared as const, it needs to be initialized at the time of
declaration. However, the object initialization while declaring is possible only with the
help of constructors.
friend function is a friend of a class that is allowed to access to Public, private, or protected
A
data in that same class. If the function is defined outside the class cannot access such
information.
A class’s friend function is defined outside that class’s scope, but it has the right to access all
private and protected members of the class. Even though the prototypes for friend functions
appear in the class definition, friends are not member functions.
yntax:
S
class class_name {
friend data_type function_name(argument); // syntax of friend function.
};
he function can be defined anywhere in the program like a normal C++ function. The function
T
definition does not use either the keyword friend or scope resolution operator.
Characteristics of friend function:
● friend function can be declared in the private or public section of the class.
A
● It can be called a normal function without using the object.
● A friend function is not in the scope of the class, of which it is a friend.
● A friend function is not invoked using the class object as it is not in the class’s scope.
● A friend function cannot access the private and protected data members of the class
directly. It needs to make use of a class object and then access the members using the
dot operator.
A friend function can be a global function or a member of another class.
●
virtual function is a member function of a class, and its functionality can be overridden in its
A
derived class. This function can be implemented by using a keyword called virtual, and it can be
given during function declaration.These functions help to achieve runtime polymorphism.
A virtual function can be declared using a token(virtual) in C++. It can be achieved in C/Python
Language by using function pointers or pointers to function.
ote :Every non-static method in Java is a virtualfunction except for final and private methods.
N
The methods that cannot be used for the polymorphism is not considered as a virtual function.
pure virtual function is only declared in the parent class. It is also referred to as an abstract
A
function. Pure virtual functions do not contain any definition in the base class. They must be
redefined in the subclass for the implementation needed.
pure virtual function is a function which can be overridden in the derived class but cannot be
A
defined. A virtual function can be declared as Pure by using the operator =0.
73. What does the keyword virtual represented in the method definition?
he super keyword is used to invoke the overridden method, which overrides one of its
T
superclass methods. This keyword allows to access overridden methods and also to access
hidden members of the superclass
When do you use the super keyword:
● Super is a Java keyword used to identify or refer parent (base) class.
● We can use super to access super class constructor and call methods of the super
class.
● W hen method names are the same in super class and sub class, to refer super class,
the super keyword is used.
● To access the same name data members of parent class when they are present in
parent and child class.
● Super can be used to make an explicit call to no-arg and parameterized constructors of
the parent class.
● Parent class method access can be done using super, when child class has method
overridden.
hen we create an instance of class, i.e. objects, we use the Java keyword new. It allocates
W
memory in the heap area where JVM reserve space for an object. Internally, it invokes the
default constructor as well.
inding is a mechanism creating link between method call and method actual implementation.
B
Binding is nothing but the association of a name with the class.
● p
rivate, final and static members (methods and variables) use static binding while for
virtual methods (In Java methods are virtual by default) use dynamic binding.
he initializer list is used to directly initialize data members of a class. An initializer list starts
T
after the constructor name and its parameters. The list begins with a colon ( : ) and is followed
by the list of variables that are to be initialized – all ofthe variables are separated by a comma
ith their values in curly brackets. Using an initialization list is almost identical to doing direct
w
initialization (or uniform initialization in C++11).
Syntax:
onstructorname(datatype value1, datatype value2):datamember(value1),datamember(value2)
C
{
...
}
Extra Questions:
1. W
hat is return type of an constructor
Ans.Constructors don’t have a return type, not evenvoid.
2. D
oes python support overloading and overriding.
Ans.Python does not support method overloading. Wemay overload the methods but
can only use the latest defined method.
But it supports overriding.
3. W
hat is singleton class?
Ans.In object-oriented programming, a singleton classis a class that can have only one
object (an instance of the class) at a time. After the first time, if we try to instantiate the
Singleton class, the new variable also points to the first instance created.
emember the key points while defining class as a singleton class that is while
R
designing a singleton class:
● Make a constructor private.
● Write a static method that has the return type object of this singleton class. Here,
the concept of Lazy initialization is used to write this static method.
4. W
hy multiple inheritance is supported in C++ and not in java?
Ans.Java does not support multiple inheritance.Thereason 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. However, a class can implement one or more interfaces, which has helped Java
get rid of the impossibility of multiple inheritances.
In C++ we have virtual functions to avoid diamond ambiguity.
5. If a class with all static methods has better performance, Why don't we make all
functions static.
Ans. Static methods are more efficient in terms ofmemory and time. They are slightly
faster than instance methods because in instance methods, you are also working with an
implicit “this” parameter.There is no need to passthe "this" reference in static
methods.That reference is passed in the ECX register so there is no additional stack
space required.Eliminating that parameter gives aslight performance boost in most
programming languages.
But static methods has its limitations too:
1. Static methods can not be overridden, since they areresolved using static
binding by the compiler at compile time. However, we can have the same name
methods declared static in both superclass and subclass, but it will be called
Method Hidingas the derived class method will hidethe base class method.
2. Static methods can’t access instance methods and instance variables
directly.They must use reference to object. And staticmethod can’t usethis
keyword as there is no instance for ‘this’ to refer to.
6. What will happen if I don't write initialisemain method with static in JAVA,
Ans.Bootstrap class loader searches for main functionin the class file, if main function
is not declared as static, it will throw an error because declaring function as static allows
it to be called without instantiating that class file where the main function is.
main method should always bepublic static void main(String[]args)
if you try to change or miss anything, it will give you an error.
● m ain method should be public because JVM should find it when class is
loaded.
● it should be static because there is no instance of the main method. It should
be called after loading the class. Hence static.
● it is void because it doesn’t have any return type
● O verloading assignment operator in C++ copies all values of one object to
another object
● The object from which values are being copied is known as an instance
variable.
● A non-static member function should be used to overload the assignment
operator.
8. What is the difference between encapsulation and abstraction?
------------------------------------------------------------------------------------------------------------------
—
What is “auto” keyword and where we can not use it?
—--------------------------------------------------------------------------------------------------------------------