0% found this document useful (0 votes)
85 views

Object Oriented Programming Interview Questions & Answers

Object-oriented programming models real-world objects like their attributes and behaviors. Some advantages of OOP include simplicity, modularity, extensibility, and reusability. Classes define common attributes and behaviors, while objects are instances of classes. Encapsulation separates an object's internal implementation from its external interface. Abstraction focuses on essential object properties and hides unnecessary details.

Uploaded by

Nirmal Silwal
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views

Object Oriented Programming Interview Questions & Answers

Object-oriented programming models real-world objects like their attributes and behaviors. Some advantages of OOP include simplicity, modularity, extensibility, and reusability. Classes define common attributes and behaviors, while objects are instances of classes. Encapsulation separates an object's internal implementation from its external interface. Abstraction focuses on essential object properties and hides unnecessary details.

Uploaded by

Nirmal Silwal
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 58

1)What is Object Oriented Programming?

Ans:- Object-oriented programming (OOP) is a


programming based on the concept of "objects",
which are data structures that contain data, in
the form of fields, often known as attributes and
code in the form of procedures, often known as
methods.
2)What are the advantages of Object Oriented
Programming?
1. Ans:- Simplicity: OOPS programming objects
model real world objects, so the complexity is
reduced and the program structure is clear.
2. Modularity: Each object forms a separate
entity whose internal workings are decoupled
from other parts of the system.
3. Modifiability: It is easy to make minor
changes in the data representation or the
procedures in an OO program. Changes inside
a class do not affect any other part of a
program, since the only public interface that the
external world has to a class is through the use
of methods.
4. Extensibility: Adding new features or
responding to changing operating
environments can be solved by introducing a
few new objects and modifying some existing
ones.
5. Maintainability: Objects can be maintained
separately, making locating and fixing
problems easier.
6. Reusability: Objects can be reused in
different programs.

3) what are the advantages of oops over pop?


ans:-

1)OOPs makes development and


maintenance easier where as in Procedure-
oriented programming language it is not
easy to manage if code grows as project
size grows.
2)OOPs provides data hiding whereas in
Procedure-oriented programming language
a global data can be accessed from
anywhere.
3)OOPs provides ability to simulate real-
world event much more effectively. We can
provide the solution of real word problem if
we are using the Object-Oriented
Programming language.
4)What is the difference between class and object?
Ans:- class is just a blueprint. A class defines
the available characteristics and behavior of
a set of similar objects.
e.g. Car class defined has so many attributes
and behaviour such as start(),stop(),accelerate()
etc,
object or instance is basic runtime entity. E.g.
Maruti Alto, WaganR, Maruti Swift etc.

3)give some real life examples of Object.

Ans:- The world can be considered to consist


of many objects. Objects will have attributes
and behaviors.

A water-heater is a simple example of an


object. It has certain attributes or properties
(like color, size, maximum and current
temperatures etc.) and there are certain
behaviors associated with the water-heater
(like switching on the heater, increasing the
temperature or heating for a specified time
interval, switching off the heater etc.).
These are actions that can be performed on
the heater. Or in other words they are
actions which can modify certain properties
of the heater (for instance by switching on
the heater the current temperature of the
heater will change).

A car is another example of an object. It has


a lot of attributes such as fuel capacity,
current speed, top speed, number of
wheels, type of gearbox etc. There are also
a lot of operations which you can perform
on this object. For example: you can
accelerate the car, apply brakes etc.

5) What do you mean by ADT?


Ans:- ADTs stand for abstract data types. Classes
which provide data abstraction are referred to as
ADTs.
6) What is Abstraction?
Ans:- Abstraction is the process of extracting
the relevant properties of an object while
ignoring nonessential details relative to the
perspective of the viewer.
e.g.
 A doctor sees (abstracts) the person as
patient.  The doctor is interested in name,
height, weight, age, blood group, 
previous or existing diseases etc of a
person whereas An employer sees
(abstracts) a person as Employee. The
employer is interested in name, age, 
health, degree of study, work
experience etc of a person.  
 For a sales tracking system relevant attributes
of a salesperson might be: name, number of
vehicles sold, value of vehicles sold, list of
customers, commission rate, total
commissions.
 A car dealer might view a car from the
standpoint of its selling features. Relevant
properties include price, color, optional
equipment, and length of warranty. On the
other hand , mechanic views the car from the
standpoint of systems that require
maintenance. Here relevant properties
include the type of oil, the size of oil filter,
and the number and type of spark plug.
7) What is Encapsulation?
Ans:- Encapsulation is the process of
separating the aspects of an object into
external and internal aspects. The external
aspects of an object need to be visible or
known , to other objects in the system. The
internal aspects are details that should not
affect other parts of the system. Hiding the
internal aspects of an object means that they
can be changed without affecting external
aspects of the system.
e.g.
a) Encapsulation in a Real World Elevator
System
Any useful elevator has a mechanism, such as
buttons, that allow a passenger to select his or her
destination floor. (we have two objects here
Elevator and Person ). Pressing a button is a very
easy action to perform for the user of the elevator.
However, for the elevator faced with many
conflicting simultaneous requests from many
different people, it can be a complicated matter
deciding which floor to go to and fulfill the request
of each traveler appropriately.
e.g Person A might enter the elevator at floor 3
and request to go to floor 30. However, another
person, B, has already pressed the button on floor
1 requesting to be picked up there. If the elevator
goes directly to floor 30 with person A (but without
B), person A will get there as fast as he or she
could ever expect. However, person B has to wait.
Perhaps, by merely moving two floors down, the
elevator could have taken both people to a higher
floor at the same time, saving time and power.
Instead, the elevator has to go all the way up to
floor 30 and then back down to pick up B. With
many people constantly requesting elevators and
destination floors, the matter gets much more
complex as far as implementation logic is
concerned.
At least a couple of other aspects complicate
matters further for our trusted elevator:
 Several elevators are probably working
together to transport people between the
different floors. They consequently need a
"team" approach to fulfill as many requests as
possible. Densely populated buildings with large
amounts of traffic between floors require
approximately two elevators for every three
floors. Thus, a 60-floor building would require
about 40 elevators.
 Certain floors are more likely to be visited and
have pick-me-up requests than other floors.
These probabilities might vary throughout the
day. If the elevators can somehow remember
these patterns, they can optimize the efficiency
of the sequence of floors visited.
Sophisticated algorithms have been constructed
running inside computers that control the
movements of the elevators, allowing them to
serve as many people as possible, fast and
efficiently.
This was a bit of elevator talk, but it leads us to an
essential observation.
It is easy for a person to press a button and
thereby use the hidden complex services
(algorithms, engines, gears, wires, data about
current speed, maximum speed, and so on)
provided by the elevator. Thus, the ignorant
passenger, in terms of elevator technology, can
easily utilize the services of the elevator to
accomplish his or her tasks of the day.
Not only is this concealment of elevator data,
algorithms, and mechanics an advantage for
travelers who do not want to deal with complex
matters that are irrelevant to them; but it also
improves the reliability of the elevator itself. No
unauthorized and incompetent person can gain
access to the inner control mechanisms of the
elevator. Imagine if the elevator was equipped with
a small "cockpit" where anybody traveling in the
elevator could tinker with the maximum speed, or
make the elevator believe it was on an incorrect
floor, or force it to move to a floor other than the
one calculated by its control algorithms. A chaotic
situation would soon prevail.
A final advantage of segregating the buttons from
the underlying elevator mechanisms is the
capability of making changes to these
mechanisms without altering the buttons and,
hence, the way it is operated. In this way, an
elevator can contain the same buttons that
everyone has become accustomed to using for
many years, while many underlying hardware and
software upgrades have taken place to keep the
system up to date.
Encapsulation in an Elevator Simulation
An elevator simulation program written in will
probably have Elevator and Person objects
along with others. Even though now inside a
computer program, a Person object will still be
able to perform the equivalent of "pressing the
button" of an Elevator object and giving it a floor
request.
Each Elevator object of the simulation probably
contains, like its real counterpart, many complex
methods and many sensitive data. For example,
many Elevator objects might, to make the
simulation particularly realistic, be equipped with
algorithms (similar to the algorithms of real world
elevators) to calculate the most efficient sequence
of floors visited.
Now the important analogy—each Person object
(and the programmer implementing it) of the
simulation should still not need or be allowed to
"know" about the inner complexities (source code)
of any Elevator object. All they should "care"
about, just like their real counterparts, is to get
from one floor to another. They don't want to be
confused about unnecessary complexities either.
They should not be allowed to tinker with the inner
workings (data and source code) of the Elevator
object, and the programmers implementing the
elevator should be able to change and upgrade
the source code without interfering with how the
Elevator object is used (operated).

To accomplish this concealment in the OO world,


we say that we encapsulate (hide) the underlying
data and source code that is irrelevant for all but
the Elevator objects themselves.
A Person object needs somehow the ability to
"express" its floor request. A method with this
capacity could arbitrarily be called
NewFloorRequest which should be a
public method in Elevator. The Elevator
object, like its real counterpart, might need to
somehow keep track of, for example, the speed at
which it is traveling and its maximum speed; these
are the instance variables (data) of the object, as
mentioned previously. The Elevator object does
not want any interference from other objects to
mistakenly change their instance variables.
Therefore, the Elevator objects declare them to
be private, making them inaccessible for other
objects.
b) an automated voice-mail system, we should be able
to change the component that handles storing the
messages without affecting other parts of the system.
For example, we might want to increase the number of
messages that a user can store. If the message-storing
system has been properly hidden and isolated, this
change should not affect how users access the system
and leave or retrieve messages.
c) How coffee vending machine works ?
You dropped in the coin, and the coffee came out of the
machine in a beautiful coffee cup. So, why didn’t you
see how the where the coffee beans, how it is prepared?
You really don’t know (unless you are the one who
designed the machine) how things are made inside the
machine, but finally you get a coffee!! Here don’t you
see a sense of Encapsulation? So, here what is actually
hidden is , the way how the coffee prepared .
So, Encapsulation is hiding of process; hence you
hide the data. Not the vice versa.
From the definition, Encapsulation is “Information
Hiding”, the information is how something is
happening inside an object? It’s just a mere data
hiding concept (though it includes data hiding).
So, when you model this coffee vending machine, you
don’t want to show out the way how a coffee is made.
So, you don’t want to show where the coffee beans,
milk and the sugar are !

So, in the CofeeVendingMachine class, prepareCoffee()


is hidden and getCoffee() is made public, so that you
will be able to send a request to the machine.
Since you have hidden the process, you don’t have any
need to show how the coffee & milk are mixed and how
it’s been brewed.

The Coffee Vending Machine encapsulates the


internal process and the ingredients (data) used
in the process.
8) What is the relationship between abstraction and
encapsulation?
Ans:- abstraction focuses upon the
observable behavior of an object, whereas
encapsulation focuses upon the
implementation that gives rise to this
behavior. abstraction is a
perspective and encapsulation is
implementation to achieve that
perspective.
9) What is Generalization and
Specialization?
Ans:- Generalization is the process of
extracting shared characteristics from two or
more classes, and combining them into a
generalized superclass , e.g. Saving , Current
and FD are having some common traits. Hence
we can have a base class “Saving” which will
contain common traits and then all the sub
classes can inherit them.
While specialization means creating new
subclasses from an existing class. If it turns
out that certain attributes, associations, or
methods only apply to some of the objects of
the class, a subclass can be created.e.g. Flexi-
Deposit is same as FD hence we can derive it
from FD and have some unique traits inside it.
Both concepts can be implemented using
inheritance only. But the order of creation of the
subclass and the superclass drives the concept
name.
The way or perspective of looking also gives the
difference between these two concepts. When
you look from the perspective of a base class, it
is generalization because the base class has
functions or operations that may be commonly
used by all of its subclasses. When you look from
the perspective of the derived class, it is
specialization because even though the common
functionalities from the super class are available,
the derived classes perform their own operations
or functions specific to the purpose of their
creation.

From the above figure, if you see from the


perspective of the Train, then it is
Generalization. The common functions or
operations of both the Passenger and Goods
Trains are put into the Train such as startTrain,
stopTrain, fillFuel. That is, the generic operations
of any subclass of Train are included in Train.

If you see from the perspective of the subclasses


(Passenger Train or Goods Train), then it is
Specialization. The common functions of the
superclass (Train) are also included with the
specific functions of the subclass such as
boardPassengers, fillWater, fillPantryResources in
case of Passenger train and loadGoods,
unloadGoods in case of Goods train making the
subclass, a class for a specific or special function.

Note: In case of Generalization, it is not


necessary that the superclass (Train) should know
about the existence of its subclasses (Passenger
Train and Goods Train). In case of Specialization,
the subclass will always know its superclass.

10) Explain Association, Aggregation and


Composition.
Ans:-             Association 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 is a specialize form of
Association where all object have their own
lifecycle but there is ownership and child
object cannot belongs to another parent
object. Let’s take an example of Department
and teacher. A single teacher cannot
belongs to multiple departments, but if we
delete the department teacher object will
not destroy. We can think about “has-a”
relationship.
 
            Composition 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. 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 cannot belongs to
two different house if we delete the house
room will automatically delete. 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.
11) Explain Object Composition vs Inheritance.
Ans:- Object Composition vs. Inheritance
Object composition and inheritance are two techniques
for reusing functionality in object-oriented systems.

Class inheritance, or sub classing, allows a subclass'


implementation to be defined in terms of the parent
class' implementation. This type of reuse is often called
white-box reuse. This term refers to the fact that with
inheritance, the parent class implementation is often
visible to the subclasses.

Object composition is a different method of reusing


functionality. Objects are composed to achieve more
complex functionality. This approach requires that the
objects have well-defined interfaces since the internals
of the objects are unknown. Because objects are treated
only as "black boxes," this type of reuse is often called
black-box reuse.

Pros and Cons


The advantage of class inheritance is that it is done
statically at compile-time and is easy to use. The
disadvantage of class inheritance is that the subclass
becomes dependent on the parent class implementation.
This makes it harder to reuse the subclass, especially if
part of the inherited implementation is no longer
desirable. Another problem with class inheritance is that
the implementation inherited from a parent class cannot
be changed at run-time.

In object composition, functionality is acquired


dynamically at run-time by objects collecting references
to other objects. The advantage of this approach is that
implementations can be replaced at run-time. This is
possible because objects are accessed only through their
interfaces, so one object can be replaced with another
just as long as they have the same type. In addition,
since each object is defined in terms of object
interfaces, there are less implementation dependencies.
The disadvantage of object composition is that the
behaviour of the system may be harder to understand
just by looking at the source code. A system using
object composition may be very dynamic in nature so it
may require running the system to get a deeper
understanding of how the different objects cooperate.

How inheritance can be dangerous?


 

Let’s take an example

 public class X{

   public void do(){

    }

Public Class Y extends X


{
   public void work()
{
do();
}
}

As clear in above code , Class Y has very strong


coupling with class X. If anything changes in
superclass X , Y may break dramatically. Suppose
In future class X implements a method work with
below signature

public int work()


{

Change is done in class X but it will make class Y


break. So this kind of dependency can go up to
any level and it can be very dangerous. Every time
superclass might not have full visibility to code
inside all its subclasses and subclass may be keep
noticing what is happening in superclass all the
time. So we need to avoid this strong and
unnecessary coupling.

How does composition solve this issue?

Let’s see by revising the same example

public class X
{
public void do()
{

}
}

Public Class Y
{
X x=new X();

public void work()


{

x.do();

Here we are creating reference of X class in Y


class and invoking method of X class by creating
an instance of X class.
Now all that strong coupling is gone. Superclass
and subclass are highly independent of each other
now. Classes can freely make changes which
were dangerous in inheritance situation.
Second very good advantage of composition in
that It provides method calling flexibility For
example

interface R
{
void do();
}
class X implements R
{
void do()
{
Do it in a X way
}
}
class Y implements R
{
void do()
{
Do it in a Y way
}
}
class App
{
R ref;
public App(R ref)
{
this.ref=ref;
}

public void work()


{

ref.do(); // black-box reuse

}
}

public class Demo


{
public static void main(String args[])
{
R ob1=new X();
App first=new App(ob1);
first.work();
ob1=new Y();
App second=new App(ob1);
second.work();
}

In App class using ref reference we can invoke


methods of X class as well as Y class. This
flexibility was never there in inheritance

Good to know: 
        1. composition is easily achieved at runtime
while inheritance provides its features at           
compile time 

        2. composition is also known as HAS-A


relation and inheritance is also known as IS-A      
relation

Example – Combining Inheritance and Composition

class FourWheeler
{
void start()
{
// some default behavior
}
void stop()
{
// some default behavior
}
}
interface Engine
{
void start();
void stop();
}
class MarutiEngine implements Engine
{
@Override
public void start()
{
// maruti specifics
}

@Override
public void stop()
{
// maruti specifics
}
}
class ToyotaEngine implements Engine
{
@Override
public void start()
{
// Toyota specifics
}

@Override
public void stop()
{
// Toyota specifics
}
}
class Car extends FourWheeler
{
private Engine engine; // program to
interface
private String type;
public Car(String type)
{
this.type=type;
engine=new MarutiEngine();
}
void start()
{
super.start();
engine.start(); // black-box reuse
}
void stop()
{
super.stop();
engine.stop(); // black-box reuse
}
}
public class Demo1
{
public static void main(String[]
args)
{
Car mycar=new Car("Maruti");
mycar.start();
// some more statements

mycar.stop();
}
}

12) What is polymorphism?


Ans:- Polymorphism is an ability to appear in
many forms. It refers to the ability of the
system to call correct implementation of
methods with the same name.
Example 1

Account
getRateOfInterest() //
method

SavingAccount CurrentAccount
FixedDeposit RecurringDeposit // overriding
“getRateOfInterest()” method.

A method “calcInterest( Account ref )


The above method, “pass type of account


( Saving/Current/FD/RD ) [ upcasting ]” . The
method will calculate interest for that particular
account type. [ late binding ]

Example 2:-
An abstract class called "Animal".

On it Animal has a method called "MakeASound".


Now, since Animal is abstract - there is no code
inside of the MakeASound method because
Animal expects a more specific type to define how
MakeASound works.

So lets say you make a "Dog" class that inherits


the "Animal" class. Because Dog inherits Animal -
Dog is required to define functionality for the
MakeASound method. Inside that method for Dog,
you would put "Console.WriteLine("Bark");"

Now let's say you have a "Cat" class. Inside the


MakeASound method for the cat class you would
put "Console.WriteLine("Meow");"

A method “checkSound(Animal ref) “ can take


any animal (Dog/Cat ) [ upcasting ].
Using ref, we will invoke “MakeASound()” method
(late binding), which will correctly invoke the
method of the object we have passed.
13) What is method overloading?
Ans:- defining more than one functions with the
same name but with different arguments is
known as “Method Overloading”
e.g.
Account class

openAccount(int accno) // to allow zero


balance account.
openAccount(int accno,double balance) //
open account with some balance.
Another example:
Let’s say Samsung mobile have the 5MP camera
available i.e. – it is having a functionality of
CameraClick(). Now same mobile is having
Panorama mode available in camera, so
functionality would be same but with mode.

1. public class Samsumg : Mobile  
2. {  
3.     public void GetWIFIConnection(
)  
4.     {  
5.         Console.WriteLine("WIFI co
nnected");  
6.     }  
7.   
8.     //This is one mwthod which sho
ws camera functionality  
9.     public void CameraClick()  
10.     {  
11.         Console.WriteLine("Camera 
clicked");  
12.     }  
13.   
14.     //This is one overloaded metho
d which shows camera functionality as 
well but with its camera's different 
mode(panaroma)  
15.     public void CameraClick(string 
CameraMode)  
16.     {  
17.         Console.WriteLine("Camera 
clicked in " + CameraMode + " Mode"); 
 
18.     }  
19. }  

So, in this example, CameraClick() method is


overloaded.

14) What is the difference between Early Binding and


Late Binding?
Ans:- Early vs. Late binding
Early binding refers to events that occur at compile
time. e.g. normal function calls, overloading of
functions and operator.
The main advantage to early binding is efficiency.
Because all information necessary to call a function is
determined at compile time, these types of function
calls are very fast.

late binding refers to function calls that are not


resolved until runtime. virtual functions are used to
achieve late binding. The object and the function are
not linked until runtime. The main advantage of late
binding is flexibility.
However because a function call is not resolved until
runtime, late binding can make for somewhat slower
execution times.
15) What is Loose Coupling and tight Coupling?
Ans:- Coupling is the degree to which one object
knows about another object. If the only
knowledge that object A has about object B, is
what B has exposed through its interface
(Program to interface), then object A and object
B are said to be loosely coupled... on the other
hand, object A relies on object B’s
implementation (Program to implementation),
then A and B are said to be tightly coupled.

class Car extends FourWheeler


{
private MarutiEngine engine=new
MarutiEngine; // tight coupling ,
program to implementation
}

class Car extends FourWheeler


{
private Engine engine; // loose
coupling , program to interface
public Car(Engine engine) // can be
provided with any implementation
during runtime.
{
This.engine=engine;
}
}

16) What is Cohesion?


Ans:- cohesion is all about how a single
class is designed. The term "cohesion" is used
to indicate the degree to which a class has a
single, well-focused purpose. Cohesion is a
subjective concept. The more focused a class
is, the higher its cohesiveness - a good thing.
The key benefit of high cohesion is that such
classes are typically much easier to maintain
(and less frequently changed) than classes
with low cohesion. Another benefit of high
cohesion is that classes with a well-focused
purpose tend to be more reusable than other
classes.

17) What is early binding ? give examples.


Ans:- when method call is resolved during
compile/linking time, it is known as early
binding. E.g.
Operator overloading and function overloading.
4)How composition is better than inheritance?
Ans:- Favour composition over inheritance is a one of
the popular object oriented design principle, which
helps to create flexible and maintainable code in
object oriented languages.

1) In case of extending a class, you only get


facilities which are available at compile time.
e.g:
Class FileReader
{
Read()
{
// code to read from file
}
}
Class FileWriter
{
Write()
{
// code to write to file
}
}

Class MyApplication:FileWriter, FileReader


{

Perform()
{
Read() // of FileReader // tight
coupling
Write() // of FileWriter // tight coupling
}
}

drawbacks:
• Tight coupling- if base class ( FileReader or
FileWriter) is changed, sub class
(MyApplication) will break.
• inheritance breaks encapsulation. white-box
reuse. That is ,with inheritance, the parent class
implementation is often visible to the subclasses.

2) Composition offers better test-ability of


a class than Inheritance. If one class is
composed of another class, you can easily
create Mock Object representing composed
class for the sake of testing. Inheritance
doesn't provide this luxury. In order to test
derived class, you must need its super
class. Since unit testing is one of the most
important thing to consider during software
development, especially in test driven
development, composition wins over
inheritance.

e.g.

interface Reader
{
Void read();
}
Interface Writer
{
Void write();
}
Class FileReader implements Reader
{
Void read()
{
Code to read from file
}
}
Class FileWriter implements Writer
{
Void write()
{
Code to write to file
}
}

Class MyApplication
{
// program to interface, enables loose
coupling
Reader ref1;
Writer ref2;

Public MyApplication(Reader
ref1,Writer ref2)
{
This.ref1=ref1;
This.ref2=ref2;
}

Void perform()
{
Ref1.read(); // late binding
Ref2.write(); // late binding
}
}

In the above example “MyApplication” is


composed of “Reader” and “Writer”.

Advantages:
• black-box reuse as it does not break
encapsulation. MyApplication knows only
selected functionalities from “Reader” and
“Writer”.
• Loose coupling, program to interface.
During runtime any implementations
(such as “FileReader” or
“SocketReader” and “FileWriter” or
“SocketWriter”) can be passed to
“Reader” or “Writer” respectively and
“read()” method can be invoked on it
polymorphically.

Most of the object oriented design


patterns mentioned by Gang of Four
favour Composition over Inheritance.
In short, don't use Inheritance just for the sake of
code reuse, Composition allows more flexible and
extensible mechanism to reuse the code.
Though there are certainly some cases where
using Inheritance makes much sense like when
a genuine parent child relation exists, but most
of time it makes sense to favour composition over
inheritance for code reuse.

15) what is “black-box-reuse” and “white-box-reuse”?


Ans: Class inheritance, or sub classing, allows a
subclass' implementation to be defined in terms of the
parent class' implementation. This type of reuse is often
called white-box reuse. This term refers to the fact that
with inheritance, the parent class implementation is
often visible to the subclasses.

Object composition is a different method of reusing


functionality. Objects are composed to achieve more
complex functionality. This approach requires that the
objects have well-defined interfaces since the internals
of the objects are unknown. Because objects are treated
only as "black boxes," this type of reuse is often called
black-box reuse.
16) Give an example between tight coupling and loose
coupling.
Ans:- Program wise Difference between Tight
Coupling and Loose Coupling?

Tight Coupling Between two Objects

class Traveler
{
Car c=new Car();
void startJourney()
{
c.move();
}
}

class Car
{
void move()
{
// logic...
}
}

Loose Coupling Between two Objects

class Traveler
{
Vehicle v;
public void setV(Vehicle v)
{
this.v = v;
}

void startJourney()
{
v.move();
}
}
//=========================Interface======
==============================
Interface Vehicle
{
void move();
}
//====================Multiple class
implement vehicle interface.
First class====
class Car implements Vehicle
{
public void move()
{
// logic
}
}
//===================
Second class================
class Bike implements Vehicle
{
public void move()
{
// logic
}
}

17) Explain abstract class


Ans:- in java as soon as u define a class with
"abstract" keyword, class becomes abstract.
abstract class can not be instantiated.
abstract class can contain abstract as well as non-
abstract methods.
abstract method is a method which is declared
with "abstract" keyword.
a child class of an abstract class has to provide
implementation to the method which is declared
"abstract" in parent class or else make child class
also "abstract".

18) What is the need of abstract class?


Ans:- Abstract classes let you define some behaviors;
they force your subclasses to provide others. For
example, if you have an application framework, an
abstract class may provide default services such as
event and message handling. Those services allow your
application to plug in to your application framework.
However, there is some application-specific
functionality that only your application can perform.
Such functionality might include startup and shutdown
tasks, which are often application-dependent. So
instead of trying to define that behavior itself, the
abstract base class can declare abstract shutdown and
startup methods. The base class knows that it needs
those methods, but an abstract class lets your class
admit that it doesn't know how to perform those
actions; it only knows that it must initiate the actions.
When it is time to start up, the abstract class can call
the startup method. When the base class calls this
method, Java calls the method defined by the child
class.

19) Why can’t we instantiate abstract class?


Ans:- An Abstract class represents an abstract concept.
Take an example of vehicle class. You cannot build a
vehicle that is not something more specific.
Abstract classes represent such abstract concepts as
vehicle. Hence the idea of instantiating one doesn’t
make sense because to actually instantiate it you need
to know what you're instantiating.
An abstract class is not complete! The author marked it
abstract to tell you that some implementation is
missing in the code. The author has done some of the
work, but you must fill in some bits yourself to get it
working. The abstract keyword ensures that no one
would accidentally initiate this incomplete class.
Because it is abstract which in simple terms means not
real, or an imaginary thing. you have to make a real
class that is based on the abstract ideas to be able to
instantiate it.
Simply said, because it is possible that some
methods are not implemented. In the case of
an interface, none of the methods are
implemented.

If you would be able to create an instance,


and call a non-implemented method, what
code should be executed? Not that of the
class / interface itself, since there is no code
to execute.

The answer of "why you can't instantiate an abstract


class " is because when you use the keyword "abstract
" you're saying: "I'll provide implementation details of
this class in one of my child classes"
Abstract class means incomplete class. We do not
know implementations for some of the methods. So in
programmatic way we are informing that at this point, I
don’t know the implementation. So whoever want to
use, create a concrete class. Logically this is the reason
for not Instantiating the abstract class.
Abstract classes are ideas and concrete classes are
things that we can describe and touch if they were in
the real world.
20) Can abstract class have constructors?
Ans:- Yes, abstract class can declare and define
constructor in Java. Since you cannot create
instance of abstract class, constructor can only
be called during constructor chaining, i.e. when
you create instance of
concrete implementation class. Now question
arises what is the purpose of constructor, if you
cannot instantiate abstract class? Well, it can
still be used to initialize common variables,
which are declared inside abstract class, and
used by various implementations. Also even if
you don’t provide any constructor, compiler will
add default no argument constructor in abstract
class, without that your subclass will not
compile, since first statement in any constructor
implicitly calls super(), default super class
constructor.
21) What is “this”?
Ans:- member functions are having only one
copy in memory irrespective of no. of objects
created.
how does member function comes to know
which object they have to work for?
Answer is "this pointer or reference".
"this" pointer or reference is a pointer pointing
to current object or calling object.
when u call any member function using an
object, "this" pointer or reference holds the
address of that object. using "this" pointer
member function will come to know to which
object they have to work for. Infact when u
invoke any member function compiler secretly
pass first argument as “this” pointer or
reference.

22) Explain static member and member function.


Ans:- static members
static members are allocated memory as soon as
class is loaded. i.e. even before any object is
created. Since they are not associated with
objects, they are having only one copy in the
memory. In order to access static member, no
need to use object.
application of static member
suppose you are designing "Account" class.
accout_id,name,type and balance are different
for different instances,but rate_of_interest will
be common for all the objects. Hence
rate_of_interest will be the static member in
this case.
if you want to keep track of number of objects
created of a class, you can have static member
"int cnt" which will be incremented every time
object is created.

23) explain linking of Base class, Sub class and


Base object, Sub object.
Ans:- Base class and Sub class are linked i.e. if u
make any changes in Base class that will reflect in
Sub class.
Base Object and Sub object are not linked. If u make
any changes in base object Sub object will not be
reflected.
24) How will you relate unrelated classes or
how will you achieve polymorphism without
using base class?
Ans:- suppose, we have 3 objects from unrelated
classes.

Vehicle IFlying - interface


Plane fly() - method

Superhero
Superman

Animal
Bird

IFlying f=list.nextObj();

Here list contains all “Plane” or “Bird” or “Superhero”


objects.

f.fly(); // late binding


this is polymorphism without using base class. i.e. using
base interface.
So , with the help of “IFlying” interface, we have related
all unrelated classes.
U can implement Polymorphism through Common
Interface among unrelated classes.

Apply interface when u don’t have common base class.


Apply base class when u have related classes.

25) What is Association,Aggregation and


Composition?
Ans:
Association 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 is a specialize form of
Association where all object have their own
lifecycle but there is ownership and child
object cannot belongs to another parent
object. Let’s take an example of Department
and teacher. A single teacher cannot
belongs to multiple departments, but if we
delete the department teacher object will
not destroy. We can think about “has-a”
relationship.
 
            Composition 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. 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
cannot belongs to two different house
if we delete the house room will
automatically delete. Let’s take
another example relationship between
Questions and options. Single
questions can have multiple options
and option cannot belong to multiple
questions. If we delete questions
options will automatically delete.

Aggregation is a special case of association. A


directional association between objects. When an
object ‘has-a’ another object, then you have got an
aggregation between them.
eg: Room has a table, but the table can exist
without the room.
class Room {

private Table table;

void setTable(Table table) {


this.table = table;
}

}
Composition is a special case of aggregation.
Composition is more restrictive. When there is a
composition between two objects, the composed
object cannot exist without the other object. This
restriction is not there in aggregation. eg: rooms in
a house, which cannot exist after the lifetime of the
house.
class House {
private Room room;

House(Room roomSpecs) {
room = new Room(roomSpecs);
}

What is Dependency?
When one class depends on another
because it uses that at some point in
time then this relationship is known as
Dependency. One class depends on
another if the independent class is a
parameter variable or local variable of a
method of the dependent class. A
Dependency is drawn as a dotted line
from the dependent class to the
independent class with an open
arrowhead pointing to the independent
class.

What is the difference between Association and


Dependency?
The main difference between Association
and Dependency is in case of Association
one class has an attribute or member
variable of the other class type but in
case of Dependency a method takes an
argument of the other class type or a
method has a local variable of the other
class type.

26) What is Diamond Problem?

Ans: Suppose we have two classes B and C


inherit from A, and class D inherits from
both B and C. ... now when we instantiate
class D, there exists two copies of A (via B
and C )inside D object. When u invoke any
method of A class using object of D, it
creates ambiguity that is compiler does not
know u are invoking which method , the
method of A available through D or C. It is
called the "diamond problem”.
27) What is the Solution for Diamond Problem?
Ans:- Suppose we have 2 classes Lion and
Tiger that derive from the same class – in
our example above it would be class Animal.
We also have class Liger that derives
from both Lion and Tiger by using multiple
inheritance

/*
The Animal class below corresponds to
class
A in our graphic above
*/

class Animal { /* ... */ }; // base


class
{
int weight;

public:

int getWeight() { return weight;};

};

class Tiger : public Animal { /* ...


*/ };

class Lion : public Animal { /* ...


*/ }

class Liger : public Tiger, public


Lion { /* ... */ };
In the code above, we’ve given a more
concrete example of the diamond problem.
The Animal class corresponds to the
topmost class in the hierarchy (A in our
graphic above), Tiger and Lion respectively
correspond to B and C in the graphic, and
the Liger class corresponds to D.
Now, the question is what is the problem with having an inheritance hierarcy like this. Take a
look at the code below so that we can best answer that question:

int main( )
{
Liger lg ;

/*COMPILE ERROR, the code below will


not get past
any C++ compiler */

int weight = lg.getWeight();


}

In our inheritance hierarchy, we can see


that both the Tiger and Lion classes derive
from the Animal base class. And here is the
problem: because Liger derives from
both the Tiger and Lion classes – which
each have their own copy of the data
members and methods of the Animal
class- the Liger object "lg" will
contain two subobjects of
the Animal base class.

So, you ask, what’s the problem with a Liger


object having 2 sub-objects of the Animal
class? Take another look at the code above
– the call "lg.getWeight()" will result in a
compiler error. This is because the
compiler does not know whether the call
to getWeight refers to the copy of
getWeight that the Liger object lg
inherited through the Lion class or the
copy that lg inherited through the Tiger
class. So, the call to getWeight in the code
above is ambiguous and will not get past
the compiler.
Solution to the Diamond Problem
We’ve given an explanation of the diamond problem, but now we want to give you a solution
to the diamond problem. If the inheritance from the Animal class to both the Lion class and
the Tiger class is marked as virtual, then C++ will ensure that only one subobject of the
Animal class will be created for every Liger object. This is what the code for that would look
like:

class Tiger : virtual public Animal {


/* ... */ };
class Lion : virtual public Animal
{ /* ... */ }

You can see that the only change we’ve made is to add the "virtual" keyword to the Tiger and
Lion class declarations. Now the Liger class object will have only one Animal subobject, and
the code below will compile just fine:

int main( )
{
Liger lg ;

/*THIS CODE WILL NOW COMPILE OK NOW


THAT WE'VE
USED THE VIRTUAL KEYWORD IN THE TIGER
AND LION
CLASS DECLARATIONS */

int weight = lg.getWeight();


}

You might also like