What is an Object?
An object has state, exhibits some weii-defined behavior, and has a
unique identity.
An object
has state, behavior, and identity; the structure and behavior of similar
objects are defined in their common class; the terms instance and object are
interchangeable.
The state
of an object encompasses all of the (usually static) properties of tbe object
plus tbe current (usually dynamic) values of each of these properties.
Behavior
is how an object acts and reacts, in terms of its state changes and message
passing.
The state
of an object represents the cumulative results of its bebavior.
“Identity
is that property of an object which distinguishes it from all other objects
" [12].
You should always wear formal dresses for an interview - please check Why you should wear formal for an interview
Formal dresses for men
Formal dresses for women
What is a Class?
A class is
a set of objects that share a common structure and a common behavior.
OR
A class
represents a set of objects that share a common structure and a common
behavior.
What is OOAD?
Object Oriented
Analysis and Design (OOAD) is a methodology to analyze, design and develop
application using objects and their relations and message based communication
to each other. Everything in OOAD is visualized in terms of objects and
classes. OOAD introduced a paradigm shift from thinking and programming
procedurally to objects oriented programming. This approach helps in designing
complex real time systems with ease. The features like Data Abstraction and
Encapsulation, Inheritance and Polymorphism form fundamentals of object
oriented programming.
Advantages:
- Enhanced
Reusability
- Modular
approach towards problem solving which will be
- Better
Maintainability
Better Performance if system is designed cautiously using OOAD concepts
What is OOP?
Object-oriented
programming is a method of implementation in which programs are organized as
cooperative collections of objects, each of which represents an instance of
some class, and whose classes are all members of a hierarchy of classes united
via inheritance relationships.
What is OOD?
Object-oriented
design is a method of design encompassing the process of object-oriented
decomposition
and a notation for depicting both logical and physical as well as static and
dynamic models of the system under design.
What is OOA?
Object-oriented
analysis is a method of analysis that examines requirements from the
perspective of the classes and objects found in the vocabulary of the problem
domain.
What is Data Abstraction?
Data Abstraction is extraction of
essential information for a particular purpose and ingnoring the remainder of
the information, e.g. a car is consisted of an engine,air filters,a carburetor,a
gear box,a steering,a fuel tank,tyres etc.A driver of a car need not to be
bothered about several finer points of the car,he/she should know what it
requires to drive a car.Take another user, a car mechanic, he will require
different set of information in order to repair the car.
OR
An
abstraction denotes the essential characteristics of an object that distinguish
it from all other
kinds of
objects and thus provide crisply defined conceptual boundaries, relative to the
perspective of the viewer.
OR
Abstraction
focuses upon the essential characteristics of some object, relative to the
perspective of the viewer.
What is Encapsulation?
Encapsulation
is the process of compartmentalizing the elements of an abstraction that
constitute
its
structure and behavior; encapsulation serves to separate the contractual
interface of an
abstraction
and its implementation.
OR
Data Encapsulation is wrapping
informations(attributes and behaviors) within an object.A suitable example is a
class as it wraps methods and data within itself. The attributes of a class
corresponds to its data members while behaviour corresponds to member methods
of the class.
OR
Encapsulation is the mechanism to achieve
abstraction
What is the difference between
Data Abstraction and Information Hiding?
Data Abstraction is often confused with
information hiding while they altogether are two different technical
concepts.Here are few established definitions of Data Abstraction:
"A view of a problem that extracts the essential information relevant to a
particular purpose and ignores the remainder of the information." --
[IEEE, 1983]
"The essence of abstraction is to extract essential properties while
omitting inessential details." -- [Ross et al, 1975]
"Abstraction is the selective examination of certain aspects of a problem.
The goal of abstraction is to isolate those aspects that are important for some
purpose and suppress those aspects that are unimportant." -- [Rumbaugh et
al, 1991]
"An abstraction denotes the essential characteristics of an object that
distinguish it from all other kinds of object and thus provide crisply defined
conceptual boundaries, relative to the perspective of the viewer." --
[Booch, 1991]
While information hiding is not sharing the details of an object with outside
world.Here are few standard definitions of Information Hiding which will
elaborate more on this concept:
"The technique of encapsulating software design decisions in modules in
such a way that the module's interfaces reveal little as possible about the
module's inner workings; thus each module is a 'black box' to the other modules
in the system." -- [IEEE, 1983]
"The process of hiding all the details of an object that do not contribute
to its essential characteristics; typically, the structure of an object is hidden,
as well as the implementation of its methods. The terms information hiding and
encapsulation are usually interchangeable." -- [Booch, 1991]
"The principle of information hiding is central. It says that modules are
used via their specifications, not their implementations. All information about
a module, whether concerning data or function, is encapsulated with it and,
unless specifically declared public, hidden from other modules." --
[Graham, 1991]
What is Inheritance and what
are different types of it?
Inheritance is a mechanism by which a specific object acquires
attributes and behaviors of more general objects. In OOP terminology ,Inheritance
is the mechanism which allows a Class 'A' to inherit properties of Class 'B'
and we say 'A inherits from B' or in other words B is a 'Super class'/'Parent
class' while A is a 'Subclass'/'Child class'. A typical example of inheritance
is a family tree which consists of son, father, grandfather, great grandfather
and so on. The different types of Inheritance are:
1.Single Inheritance
2.Multiple Inheritance
3.Multilevel Inheritance
4.Hierarchical Inheritance
5.Hybrid Inheritance
In single inheritance, a class inherits implementation from only one super
class. For example, if class B inherits from class A, class B will acquire all
the members declared in class A.
B------>A(Parent)
In multilevel inheritance, a class inherits from a derived class (or subclass).
For example, if class C inherits from class B, and class B inherits from class
A, class C will acquire all the members declared in class B as well as all the
members declared in class A.
C------->B------>A(Parent)
In hierarchical inheritance, many sub classes inherit from a single super
class. For example, if classes B, C, and D inherit from class A, classes B, C,
and D will acquire all the members declared in class A.
B------>A(Parent)C------>A(Parent)D------>A(Parent)
In multiple inheritance, a class inherits from several super classes. For
example, if class C inherits from both class A and class B, class C will
acquire all the members declared in class A as well as all the members declared
in class B. Multiple inheritance is not directly supported by Java but through
Interfaces one can.C------>A(Parent)C------>B(Parent)
A hybrid inheritance is a combination of any two of the above discussed
inheritance types
Why Java uses Singly rooted hierarchy?
All objects in Java are inherited from
same base class called 'Object’. In Java all objects have common interface to
implement and it makes implementation of Garbage collector lot easier in Java.
The necessary implementation is provided in base class , and the garbage
collector can then send the necessary messages to every object in the system.
Without singly rooted hierarchy, it would have been difficult to implement
garbage collection feature. It enables lot of ease to programmers not to be
bothered about memory management while development. It greatly simplifies
argument passing amongst object too on the heap. As Java started from scratch
and has no backward compatibility issues with any existing language, it was a
logical choice to use the singly-rooted hierarchy in common with most other
object-oriented programming languages.
Why does Java not support Multiple Inheritance?
Why is Java not 100% pure OOP language?
Java takes inspirations from C and C++.The native datatypes like 'char','int','float','double' are straight pick from C, which is not an Object Oriented Language.Resonably enough, Java is not a 100% pure Object Oriented Language.
What is Early Binding?
The assignment of types to variables and expressions at compilation time is known as 'Early Binding',it is also called 'static binding' and 'static typing'.
What is
Polymorphism/Late Binding?
When an object is sent a message then it does not know itself what type it is, the runtime environment will decide about function calling over an object. This feature of connecting an object with its associated message at runtime is known as Polymorphism or Late binding or Dynamic binding.
What is method overloading?
A method with changed formal parameters will lead to implementing method overloading.
int calculateSum(int i,int j)
float calculateSum(float i,int j)
double calculateSum(double i,int j)
float calculateSum(int i,float j)
What is method overriding?
The method with same signature but with changed implementation lead to method overriding and that can occur in a parent child relation of classes. A method defined in parent class can be overridden in its child class with different implementation from its base class.
An example:
We will define a base class called Circle
class Circle
{
//declaring the instance variableprotected double radius;
public Circle(double radius)
{
this.radius = radius;
}
// other method definitions here
public double getArea()
{
return Math.PI*radius*radius;
}
//this method returns the area of the circle
}// end of class circle
When the getArea method is invoked from an instance of the
Circle class, the method returns the area of the circle.
The next step is to define a subclass to override the
getArea() method in the Circle class. The derived class will be the Cylinder
class. The getArea() method in the Circle class computes the area of a circle,
while the getArea method in the Cylinder class computes the surface area of a
cylinder.
The Cylinder class is defined below.
class Cylinder extends Circle
{
//declaring the instance variableprotected double length;
public Cylinder(double radius, double length)
{
super(radius);this.length = length;
}
// other method definitions herepublic
double getArea()
{
// method overriden here
return 2*super.getArea()+2*Math.PI*radius*length;
}//this method returns the cylinder surface area
}// end of class Cylinder
When the overriden method (getArea) is invoked for an object
of the Cylinder class, the new definition of the method is called and not the
old definition from the superclass(Circle).
How is Java different
from C++?
Java is a platform independent,
object oriented language while C++ is having some of its features from C, which
is a procedural language so it is not pure object oriented. Even Java is not
100% pure object oriented.
1. Pointers are supported in C++
while not in Java. The memory management is done automatically with help of
part of JVM called Garbage Collector.
2. Multiple inheritance is not
supported in Java but supported in C++.
3. There are no structures and
unions in Java.
4. There is no scope resolution
operator in Java (::).
5. There are no destructors in Java
like C++.
6. There is no virtual keyword in
Java because all non-static method use dynamic binding.
What is UML and how is it
useful in designing large systems?
Unified Modelling Language(UML) is a notational language
which comprises of several tools and techniques to support object oriented
development.UML captures scenarios(use case diagram),object
interactions(sequence diagram),class interactions(class diagrams) and object
states(state diagrams).
UML helps in designing large and complex systems.It starts
with analysis of business requirement and coming up with basic business flow
chart and static diagrams i.e. use case diagrams which gives pictorial view of
business requirements and captures scenarios. The next step is Interaction
diagrams,which mainly consists of Sequence diagrams.A Sequence diagram tells
how objects interact with each other through message passing in most
importantly in what sequence.Then classes are identified of the system with
various class identification approaches like 'Noun Phrase Approach','CRC
Approach',this exercise results in UML class diagrams.
A modular approach helps in breaking down the complex system
where each module can further be divided into components like classes and
objects.Once the whole system is refined in terms of reusability of objects,omitting
unnecessary objects and classes.The building of skeleton code on best practices
of coding, like pattern based approach, helps in foundation of efficient code.
Is UML useful for
procedural programming ?
Procedural programming is an unstructured way of programming which consists of set of procedures/method calls/instructions to be executed sequentially in such a way to attain the objective of a program.UML can help here in a very basic way in laying out the sequence of executions of instructions.
What is a Use case and
an Actor?
Usecase
represents a particular scenario which corresponds to functional requirement(s)
of a system to be designed and developed.An Actor is a user/external program or
a system(anyone or anything), which interacts with a system.An Actor may
input/receive or both(input and receive) information from the system.
In the diagram shown below, a scenario of buying bus/train/tram ticket from a vending machine is captured through a use case diagram.Here actor is a 'Customer' as shown by a stickman and in ovals all usecases have been documented.
How to identify an
Actor?
An Actor can be identified by finding an answer for following points:
Who is:
-interacting
-benefited
-maintaining
-supplying information
-using information
-removing information Does system use an external resource?
A good/refined set of actors of system will be arrived iteratively.
What is
Generalization?
In UML , a generalization relationship is a relationship in which one
model element (the child) is based on another model element (the parent).
Generalization relationships are used in class, component, deployment, and use
case diagrams.
Generalization corresponds to inheritance implemenation amongst classes.
What is
Generalization?
An Association specifies how objects
are related to one another.To identify associations,look for verb and
prepositional phrases like 'part of','next to','works for' or 'contained
in'.While identifying implicit associations, a lot common sense and general
knowledge is required.It is very important to eleminate redundant associations
while desiging a system.The most important aspects of associations are:
Cardinality - a cardinality of one
on a given relationship end generates a Java reference, for example
public class Customer
{
Purchase purchase;
}
A cardinality of many (depicted as a
number or *) generates a Java container:
public class Customer
{
List purchases;
}
Navigability - For given an instance
of an object on one side of a association you can access an instance on the
other side. If a association can only be traversed in one direction then this
will be indicated with arrows. If there are no arrows then the association is
bi-directional.
Association end - A given class only
sees the association through the attributes set on the association end. In
other words that simple line actually represents two independent sets of data,
one for each of the two classes involved. Besides the cardinality and
navigability the most important attribute is the association end name. This
name is used to generate the getter and setter methods and in persistent
classes database column names.
The different types of associations
can be Aggregation and Composition. I will describe them in more details in
next blogs to come.
What
is Association and how it maps into a Java class?
An
Association specifies how objects are related to one another.To identify
associations,look for verb and prepositional phrases like 'part of','next
to','works for' or 'contained in'.While identifying implicit associations,a lot
common sense and general knowledge is required.It is very important to
eleminate redundant associations while desiging a system.The most important
aspects of associations are:
Cardinality - a cardinality of one on a given relationship end generates a Java
reference, for example
public class Customer
{
Purchase purchase; ...
}
A cardinality of many (depicted as a number or *) generates a Java container:
public class Customer
{
List purchases; ...
}
Navigability - For given an instance of an object on one side of a association
you can access an instance on the other side. If a association can only be
traversed in one direction then this will be indicated with arrows. If there
are no arrows then the association is bi-directional.
Association end - A given class only sees the association through the
attributes set on the association end. In other words that simple line actually
represents two independent sets of data, one for each of the two classes
involved. Besides the cardinality and navigability the most important attribute
is the association end name. This name is used to generate the getter and
setter methods and in persistent classes database column names.
The different types of associations can be Aggregation and Composition.I will
describe them in more details in next blogs to come.
What
is Aggregation and how it maps into a Java class?
An
Aggregation is an Association which denotes an "is part of"
relationship.
Take a 'Car', for example, it is consisted of an engine,a steering wheel, four
tires,seats,gear box,fuel tank,engine oil tank, air filters etc.So all constituents
of car are parts of it.
If a car is destroyed/smashed, its parts can still be used separately as spares
in other cars,so these parts have individual use even when their conatiner
entity is destroyed.
In a Java class, an aggregation can be represented from above example as :
class Car
{
List getTires();
List getSeats();
List getAllParts();
}
What
is Composition and how it maps into a Java class?
A
Composition is a tight Association and denotes "whole-part"
relationship.So when an object is destroyed then all its constituents are also
destroyed, these 'parts' have no meaning/sense in their lone existence from
their 'whole'.
The best example of Composition is a 'Human body' which is composed of two
legs,two hands,two eyes,two ears and so on.During the lifetime of a human
being,all organs make sense being part of whole,but once a human being is dead
most of these parts are also dead,unless some of his body parts are not
medically reused.
Now come to map composition to Java world, the best example is garbage
collection feature of the language.While garbage collecting objects, whole has
the responsibility of preventing all its parts being garbage collected by
holding some references to them.
It is the responsibility of whole to protect references to its parts not being
exposed to outside world.The only way to have true composition in Java is to
never let references to internal objects escape their parent's scope.
An example of Inner class as shown in the following code snippet may give you
an idea how to implement Composition in Java.
public class Human
{
public Human()
{
Brain brain = new Brain();
}
private class Brain
{
....
....
}
}
What
is Dependency and how it maps into a Java class?
A Dependency relationship means when a class
consumes/uses methods or variables from other class(supplier).So a change to
supplier class affects the consumer class as well.Here supplier is indepenedent
of any changes being made to consumer classs.
In UML class diagrams, a dependency relationship connector appears as a dashed
line with an open arrow that points from the consumer class to the supplier
class. A dependency relationship means an "import" statement.
What
is the purpose of State machine diagrams?
Objects have both attributes and behaviors. Attribute is also know as
state. When objects are incredibly complicated then to have better
understanding during different state changes one should develop one or more
state machine diagrams, formerly called state chart diagrams in UML 1.x,
describing how their instances work.
UML state machine diagrams show the various states
that an object may be in and the transitions between those states. And these
transitions are triggered by an event that can either be internal or external
to the system.An initial state of an object is called creation state,as this is
the time when an object is created, and the final state is reached when there
are no more leading out transitions from this state.
A self explanatory example of state machine diagram is given here for PIN check processing at ATM.It includes sub-machine diagrams, as shown in the diagram below:
What
are different kinds of Structure diagrams?
Structure
Diagrams as part of UML2.1:
Class diagrams
Object diagrams
Composite structure diagrams
Component diagrams
Deployment diagrams
Package diagrams
For more details on individual structure diagrams, visit following links:
Practical UML
What
are different kinds of Interaction diagrams?
The
Interaction diagrams represent how objects interact with one another through
message passing.
There are two kinds of Interaction Diagrams :
Sequence Diagram
Collaboartion Diagram
If you want to study these diagrams in detail then go through this pdf given by
OMG.
What
are different kinds of Behavior diagrams?
Behavior Diagrams include :
- Use Case Diagram (used by some methodologies during requirements gathering)
- Activity Diagram
- State Machine Diagram.
What are
the principle concepts of OOPS?
There are four principle
concepts upon which object oriented design and programming rest. They are:
- Abstraction
- Polymorphism
- Inheritance
- Encapsulation
(i.e. easily remembered as A-PIE).
What is
Abstraction?
Abstraction refers to
the act of representing essential features without including the background
details or explanations.
What is
Encapsulation?
Encapsulation is a
technique used for hiding the properties and behaviors of an object and
allowing outside access only as appropriate. It prevents other objects from
directly altering or accessing the properties or methods of the encapsulated
object.
What is the
difference between abstraction and encapsulation?
- Abstraction focuses on the outside view of an object
(i.e. the interface) Encapsulation (information hiding) prevents clients from
seeing it’s inside view, where the behavior of the abstraction is
implemented.
- Abstraction solves the problem in the design side while Encapsulation is the Implementation.
- Encapsulation is the deliverables of Abstraction.
Encapsulation barely talks about grouping up your abstraction to suit the
developer needs.
What is
Inheritance?
- Inheritance is the process by which objects
of one class acquire the properties of objects of another class.
- A class that is inherited is called a
superclass.
- The class that does the inheriting is called
a subclass.
- Inheritance is done by using the keyword
extends.
- The two most common reasons to use
inheritance are:
- To promote code reuse
- To use polymorphism
What is
Polymorphism?
Polymorphism is briefly
described as "one interface, many implementations." Polymorphism is a
characteristic of being able to assign a different meaning or usage to
something in different contexts - specifically, to allow an entity such as a variable,
a function, or an object to have more than one form.
How does
Java implement polymorphism?
(Inheritance,
Overloading and Overriding are used to achieve Polymorphism in java).
Polymorphism manifests itself in Java in the form of multiple methods having
the same name.
- In some cases, multiple methods have the same
name, but different formal argument lists (overloaded methods).
- In other cases, multiple methods have the
same name, same return type, and same formal argument list (overridden
methods).
Explain the
different forms of Polymorphism.
There are two types of
polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile
time polymorphism is method overloading. Runtime time
polymorphism is done using
inheritance and interface.
Note: From a practical programming viewpoint,
polymorphism manifests itself in three distinct forms in Java:
- Method overloading
- Method overriding through inheritance
- Method overriding through the Java interface
What is
runtime polymorphism or dynamic method dispatch?
In Java, runtime
polymorphism or dynamic method dispatch is a process in which a call to an
overridden method is resolved at runtime rather than at compile-time. In this
process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object
being referred to by the reference variable.
What is
Dynamic Binding?
Binding refers to the
linking of a procedure call to the code to be executed in response to the call.
Dynamic binding (also known as late binding) means that the code associated
with a given procedure call is not known until the time of the call at
run-time. It is associated with polymorphism and inheritance.
What is
method overloading?
Method Overloading means
to have two or more methods with same name in the same class with different
arguments. The benefit of method overloading is that it allows you to implement
methods that support the same semantic operation but differ by argument number
or type.
Note:
- Overloaded methods MUST change the argument
list
- Overloaded methods CAN change the return type
- Overloaded methods CAN change the access
modifier
- Overloaded methods CAN declare new or broader
checked exceptions
- A method can be overloaded in the same class
or in a subclass
What is
method overriding?
Method overriding occurs
when sub class declares a method that has the same type arguments as a method
declared by one of its superclass. The key benefit of overriding is the ability
to define behavior that’s specific to a particular subclass type.
Note:
- The overriding method cannot have a more
restrictive access modifier than the method being overridden (Ex: You
can’t override a method marked public and make it protected).
- You cannot override a method marked final
- You cannot override a method marked static
What are
the differences between method overloading and method overriding?
|
|
Overloaded Method |
Overridden Method |
|
Arguments |
Must change |
Must not change |
|
Return type |
Can change |
Can’t change except
for covariant returns |
|
Exceptions |
Can change |
Can reduce or
eliminate. Must not throw new or broader checked exceptions |
|
Access |
Can change |
Must not make more
restrictive (can be less restrictive) |
|
Invocation |
Reference type
determines which overloaded version is selected. Happens at compile time. |
Object type determines
which method is selected. Happens at runtime. |
Can
overloaded methods be override too?
Yes, derived classes
still can override the overloaded methods. Polymorphism can still happen.
Compiler will not binding the method calls since it is overloaded, because it
might be overridden now or in the future.
Is it
possible to override the main method?
NO, because main is a
static method. A static method can't be overridden in Java.
How to
invoke a superclass version of an Overridden method?
To invoke a superclass
method that has been overridden in a subclass, you must either call the method
directly through a superclass instance, or use the super prefix in the subclass
itself. From the point of the view of the subclass, the super prefix provides
an explicit reference to the superclass' implementation of the method.
// From subclass
super.overriddenMethod();
What is
super?
super is a
keyword which is used to access the method or member variables from the
superclass. If a method hides one of the member variables in its superclass,
the method can refer to the hidden variable through the use of the super
keyword. In the same way, if a method overrides one of the methods in its
superclass, the method can invoke the overridden method through the use of the
super keyword.
Note:
- You can only go back one level.
- In the constructor, if you use super(), it
must be the very first code, and you cannot access any this.xxx variables or methods to compute its
parameters.
How do you
prevent a method from being overridden?
To prevent a specific
method from being overridden in a subclass, use the final modifier on the
method declaration, which means "this is the final implementation of this
method", the end of its inheritance hierarchy.
public final void exampleMethod() {
// Method statements
}
What is an
Interface?
An interface is a
description of a set of methods that conforming implementing classes must have.
Note:
- You can’t mark an interface as final.
- Interface variables must be static.
- An Interface cannot extend anything but
another interfaces.
Can we
instantiate an interface?
You can’t instantiate an
interface directly, but you can instantiate a class that implements an
interface.
Can we
create an object for an interface?
Yes, it is always
necessary to create an object implementation for an interface. Interfaces
cannot be instantiated in their own right, so you must write a class that
implements the interface and fulfill all the methods defined in it.
Do
interfaces have member variables?
Interfaces may have
member variables, but these are implicitly public, static, and final- in other words, interfaces can declare only constants, not instance
variables that are available to all implementations and may be used as key
references for method arguments for example.
What
modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.
What is a
marker interface?
Marker interfaces are
those which do not declare any required methods, but signify their
compatibility with certain operations. The java.io.Serializable interface and Cloneable are typical marker interfaces. These do not
contain any methods, but classes must implement this interface in order to be
serialized and de-serialized.
What is an
abstract class?
Abstract classes are
classes that contain one or more abstract methods. An abstract method is a
method that is declared, but contains no implementation.
Note:
- If even a single method is abstract, the
whole class must be declared abstract.
- Abstract classes may not be instantiated, and
require subclasses to provide implementations for the abstract methods.
- You can’t mark a class as both abstract and
final.
Can we
instantiate an abstract class?
An abstract class can
never be instantiated. Its sole purpose is to be extended (subclassed).
What are
the differences between Interface and Abstract class?
|
Abstract Class |
Interfaces |
|
An abstract class can provide complete, default
code and/or just the details that have to be overridden. |
An interface cannot provide any code at all,just
the signature. |
|
In case of abstract class, a class may extend
only one abstract class. |
A Class may implement several interfaces. |
|
An abstract class can have non-abstract methods. |
All methods of an Interface are abstract. |
|
An abstract class can have instance variables. |
An Interface cannot have instance variables. |
|
An abstract class can have any visibility:
public, private, protected. |
An Interface visibility must be public (or)
none. |
|
If we add a new method to an abstract class then
we have the option of providing default implementation and therefore all the
existing code might work properly. |
If we add a new method to an Interface then we
have to track down all the implementations of the interface and define
implementation for the new method. |
|
An abstract class can contain constructors . |
An Interface cannot contain constructors . |
|
Abstract classes are fast. |
Interfaces are slow as it requires extra
indirection to find corresponding method in the actual class. |
When
should I use abstract classes and when should I use interfaces?
Use Interfaces when…
- You see that something in your design will
change frequently.
- If various implementations only share method
signatures then it is better to use Interfaces.
- you need some classes to use some methods
which you don't want to be included in the class, then you go for the
interface, which makes it easy to just implement and make use of the
methods defined in the interface.
Use Abstract Class when…
- If various implementations are of the same
kind and use common behavior or status then abstract class is better to
use.
- When you want to provide a generalized form
of abstraction and leave the implementation task with the inheriting
subclass.
- Abstract classes are an excellent way to
create planned inheritance hierarchies. They're also a good choice for
nonleaf classes in class hierarchies.
When
you declare a method as abstract, can other nonabstract methods access it?
Yes, other nonabstract
methods can access a method that you declare as abstract.
Can
there be an abstract class with no abstract methods in it?
Yes, there can be an
abstract class without abstract methods.
Comments
Post a Comment