Basic OOPs Interview Questions for Freshers
1. What is the difference between OOP and SOP?
Object-Oriented Programming Structural Programming
Object-Oriented Programming is
Provides logical structure to a
a type of programming which is
program where programs are
based on objects rather than just
divided functions
functions and procedures
Bottom-up approach Top-down approach
Provides data hiding Does not provide data hiding
Can solve problems of any
Can solve moderate problems
complexity
Code can be reused thereby Does not support code
reducing redundancy reusability
2. What is Object Oriented Programming?
Object-Oriented Programming(OOPs) is a type of programming that
is based on objects rather than just functions and procedures.
Individual objects are grouped into classes. OOPs implements
real-world entities like inheritance, polymorphism, hiding, etc into
programming. It also allows binding data and code together.
3. Why use OOPs?
● OOPs allows clarity in programming thereby allowing
simplicity in solving complex problems
● Code can be reused through inheritance thereby reducing
redundancy
● Data and code are bound together by encapsulation
● OOPs allows data hiding, therefore, private data is kept
confidential
● Problems can be divided into different parts making it simple
to solve
● The concept of polymorphism gives flexibility to the program
by allowing the entities to have multiple forms
4. What are the main features of OOPs?
● Inheritance
● Encapsulation
● Polymorphism
● Data Abstraction
Classes and Objects OOPs Interview Questions and
Answers
5. What is an object?
An object is a real-world entity which is the basic unit of OOPs for
example chair, cat, dog, etc. Different objects have different states
or attributes, and behaviors.
6. What is a class?
A class is a prototype that consists of objects in different states and
with different behaviors. It has a number of methods that are
common the objects present within that class.
7. What is the difference between a class and a structure?
Class: User-defined blueprint from which objects are created. It
consists of methods or set of instructions that are to be performed
on the objects.
Structure: A structure is basically a user-defined collection of
variables which are of different data types.
8. Can you call the base class method without creating an instance?
Yes, you can call the base class without instantiating it if:
● It is a static method
● The base class is inherited by some other subclass
9. What is the difference between a class and an object?
Object Class
A class is basically a template or
A real-world entity which is an
a blueprint within which objects
instance of a class
can be created
An object acts like a variable of Binds methods and data
the class together into a single unit
An object is a physical entity A class is a logical entity
Objects take memory space A class does not take memory
when they are created space when created
Objects can be declared as and
Classes are declared just once
when required
OOPs Interview Questions – Inheritance
10. What is inheritance?
Inheritance is a feature of OOPs which allows classes inherit
common properties from other classes. For example, if there is a
class such as ‘vehicle’, other classes like ‘car’, ‘bike’, etc can inherit
common properties from the vehicle class. This property helps you
get rid of redundant code thereby reducing the overall size of the
code.
11. What are the different types of inheritance?
● Single inheritance
● Multiple inheritance
● Multilevel inheritance
● Hierarchical inheritance
● Hybrid inheritance
12. What is the difference between multiple and multilevel
inheritance?
Multiple Inheritance Multilevel Inheritance
Multilevel inheritance means a
Multiple inheritance comes into
class inherits from another class
picture when a class inherits
which itself is a subclass of
more than one base class
some other base class
Example: A class describing a
Example: A class defining a child
sports car will inherit from a base
inherits from two base classes
class Car which inturn inherits
Mother and Father
another class Vehicle
13. What is hybrid inheritance?
Hybrid inheritance is a combination of multiple and multi-level
inheritance.
14. What is hierarchical inheritance?
Hierarchical inheritance refers to inheritance where one base class
has more than one subclasses. For example, the vehicle class can
have ‘car’, ‘bike’, etc as its subclasses.
15. What are the limitations of inheritance?
● Increases the time and effort required to execute a program as
it requires jumping back and forth between different classes
● The parent class and the child class get tightly coupled
● Any modifications to the program would require changes both
in the parent as well as the child class
● Needs careful implementation else would lead to incorrect
results
16. What is a superclass?
A superclass or base class is a class that acts as a parent to some
other class or classes. For example, the Vehicle class is a
superclass of class Car.
17. What is a subclass?
A class that inherits from another class is called the subclass. For
example, the class Car is a subclass or a derived of Vehicle class.
Want to upskill yourself to get ahead in your Career? Check out this
video
OOPs Interview Questions – Polymorphism
18. What is polymorphism?
Polymorphism refers to the ability to exist in multiple forms. Multiple
definitions can be given to a single interface. For example, if you
have a class named Vehicle, it can have a method named speed
but you cannot define it because different vehicles have different
speed. This method will be defined in the subclasses with different
definitions for different vehicles.
19. What is static polymorphism?
Static polymorphism (static binding) is a kind of polymorphism that
occurs at compile time. An example of compile-time polymorphism
is method overloading.
20. What is dynamic polymorphism?
Runtime polymorphism or dynamic polymorphism (dynamic binding)
is a type of polymorphism which is resolved during runtime. An
example of runtime polymorphism is method overriding.
21. What is method overloading?
Method overloading is a feature of OOPs which makes it possible to
give the same name to more than one methods within a class if the
arguments passed differ.
22. What is method overriding?
Method overriding is a feature of OOPs by which the child class or
the subclass can redefine methods present in the base class or
parent class. Here, the method that is overridden has the same
name as well as the signature meaning the arguments passed and
the return type.
23. What is operator overloading?
Operator overloading refers to implementing operators using
user-defined types based on the arguments passed along with it.
24. Differentiate between overloading and overriding.
Overloading Overriding
Child class redefining methods present in the
Two or more methods having the same name
base class with the same parameters/
but different parameters or signature
signature
Resolved during compile-time Resolved during runtime
OOPs Interview Questions – Encapsulation
25. What is encapsulation?
Encapsulation refers to binding the data and the code that works on
that together in a single unit. For example, a class. Encapsulation
also allows data-hiding as the data specified in one class is hidden
from other classes.
26. What are ‘access specifiers’?
Access specifiers or access modifiers are keywords that determine
the accessibility of methods, classes, etc in OOPs. These access
specifiers allow the implementation of encapsulation. The most
common access specifiers are public, private and protected.
However, there are a few more which are specific to the
programming languages.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.
27. What is the difference between public, private and protected access
modifiers?
Accessibility from Accessibility from Accessibility from
Name
own class derived class world
Public Yes Yes Yes
Protected Yes Yes No
Private Yes No No
28. What is data abstraction?
Data abstraction is a very important feature of OOPs that allows
displaying only the important information and hiding the implementation
details. For example, while riding a bike, you know that if you raise the
accelerator, the speed will increase, but you don’t know how it actually
happens. This is data abstraction as the implementation details are hidden
from the rider.
29. How to achieve data abstraction?
Data abstraction can be achieved through:
● Abstract class
● Abstract method
30. What is an abstract class?
An abstract class is a class that consists of abstract methods.
These methods are basically declared but not defined. If these
methods are to be used in some subclass, they need to be
exclusively defined in the subclass.
31. Can you create an instance of an abstract class?
No. Instances of an abstract class cannot be created because it
does not have a complete implementation. However, instances of
subclass inheriting the abstract class can be created.
32. What is an interface?
It is a concept of OOPs that allows you to declare methods without
defining them. Interfaces, unlike classes, are not blueprints because
they do not contain detailed instructions or actions to be performed.
Any class that implements an interface defines the methods of the
interface.
33. Differentiate between data abstraction and encapsulation.
Data abstraction Encapsulation
Solves the problem at the implementation
Solves the problem at the design level
level
Allows showing important aspects while Binds code and data together into a single unit
hiding implementation details and hides it from the world
Methods and Functions OOPs interview questions
34. What are virtual functions?
Virtual functions are functions that are present in the parent class
and are overridden by the subclass. These functions are used to
achieve runtime polymorphism.
35. What are pure virtual functions?
Pure virtual functions or abstract functions are functions that are
only declared in the base class. This means that they do not contain
any definition in the base class and need to be redefined in the
subclass.
36. What is a constructor?
A constructor is a special type of method that has the same name
as the class and is used to initialize objects of that class.
37. What is a destructor?
A destructor is a method that is automatically invoked when an
object is destroyed. The destructor also recovers the heap space
that was allocated to the destroyed object, closes the files and
database connections of the object, etc.
38. Types of constructors
Types of constructors differ from language to language. However,
all the possible constructors are:
● Default constructor
● Parameterized constructor
● Copy constructor
● Static constructor
● Private constructor
39. What is a copy constructor?
A copy constructor creates objects by copying variables from
another object of the same class. The main aim of a copy
constructor is to create a new object from an existing one.
40. What is the use of ‘finalize’?
Finalize as an object method used to free up unmanaged resources
and cleanup before Garbage Collection(GC). It performs memory
management tasks.
41. What is Garbage Collection(GC)?
GC is an implementation of automatic memory management. The
Garbage collector frees up space occupied by objects that are no
longer in existence.
42. Differentiate between a class and a method.
Class Method
A class is basically a template that binds the Callable set of instructions also called a
code and data together into a single unit. procedure or function that are to be
Classes consist of methods, variables, etc performed on the given data
43. Differentiate between an abstract class and an interface?
Basis for comparison Abstract Class Interface
Methods Can have abstract as well as
Only abstract methods
other methods
Final Variables May contain final and Variables declared are final
non-final variables by default
Accessibility of Data
Members Can be private, public, etc Public by default
Can provide the Cannot provide the
Implementation implementation of an implementation of an abstract
interface class
44. What is a final variable?
A variable whose value does not change. It always refers to the
same object by the property of non-transversity.
OOPs Interview Questions – Exception Handling
45. What is an exception?
An exception is a kind of notification that interrupts the normal
execution of a program. Exceptions provide a pattern to the error
and transfer the error to the exception handler to resolve it. The
state of the program is saved as soon as an exception is raised.
46. What is exception handling?
Exception handling in Object-Oriented Programming is a very
important concept that is used to manage errors. An exception
handler allows errors to be thrown and caught and implements a
centralized mechanism to resolve them.
47. What is the difference between an error and an exception?
Error Exception
Errors are problems that should not be Conditions that an application might try to
encountered by applications catch
48. What is a try/ catch block?
A try/ catch block is used to handle exceptions. The try block
defines a set of statements that may lead to an error. The catch
block basically catches the exception.
49. What is a finally block?
A finally block consists of code that is used to execute important
code such as closing a connection, etc. This block executes when
the try block exits. It also makes sure that finally block executes
even in case some unexpected exception is encountered.
OOPs Interview Questions – Limitations of OOPs
50. What are the limitations of OOPs?
● Usually not suitable for small problems.
● Requires intensive testing.
● Takes more time to solve the problem.
● Requires proper planning.
● The programmer should think of solving a problem in terms of
objects.
51. How much memory does a class occupy?
Classes do not consume any memory. They are just a blueprint based on which objects
are created. Now when objects are created, they actually initialize the class members
and methods and therefore consume memory
52. Is it always necessary to create objects from class?
No. An object is necessary to be created if the base class has non-static methods. But if
the class has static methods, then objects don’t need to be created. You can call the
class method directly in this case, using the class name.
53. Are class and structure the same? If not, what's the difference between a
class and a structure?
No, class and structure are not the same. Though they appear to be similar, they have
differences that make them apart. For example, the structure is saved in the stack
memory, whereas the class is saved in the heap memory. Also, Data Abstraction
cannot be achieved with the help of structure, but with class, Abstraction is majorly
used.
25. Are there any limitations of Inheritance?
Yes, with more powers comes more complications. Inheritance is a very powerful
feature in OOPs, but it has some limitations too. 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.
1. Smalltalk was the first language to be developed as a purely object-oriented
programming language?
2. Alan Kay developed the first object-oriented programming language?
3. Ada programming language supports classes, but does not support the concept of
Polymorphism.
Can you use C language to demonstrate Polymorphism-> True.
Polymorphism: If one task is performed in different ways, it is known as polymorphism.
For example: to convince the customer differently, to draw something, for example,
shape, triangle, rectangle, etc.
Why object can’t be created for abstract class?
"Abstract class has not implemented method so, we cant create the object" "The word
'Abstract' instruct the compiler to not create an object of the class".
An abstract type is defined largely as one that can't be created. You can create subtypes of
it, but not of that type itself. The CLI will not let you do this.
An abstract class has a protected constructor (by default) allowing derived types to initialize
it.
Object
● It is a instance of class
● They are inherit from [Link]
● Object is an entity which has a well-defined structure & behavior.
Object has characteristics as :
1. State
2. Behavior
3. Identity
4. Responsibility
Example - a car, a person, hard disk, pen, bank account
1. State of an object
State of an object includes the current values of all its attributes.
An attribute can be static (values will not change) or dynamic (values will be
change)
Consider a Employee has following attributes.
Static
1. Empid
2. Name static
3. Gender
Dynamic
1. Age
2. Address
3. Phone / mobile no dynamic
4. Salary
5. Education
2. Behavior of an object
Behavior is how an object acts & reacts, in terms of its state change and
message passing.
Employee is an object ===> Calculate_salary, Emp_details
● The change in state of an object reflects in its behavior.
● In above example Calculate_Salary and Emp_Details are behaviors of
an employee
3. Identity of an object
● Every object has its own identity.
● Property of an object which distinguishes it from all other objects is
an Identity.
● Single or group of attributes can be identity of an object
Employee - Empid, Name, Gender, Mobile_No
4. Responsibility of an object
Responsibility of an object is the role it serves within the system.
Example - responsibility of an employee is to carry out the work given & get the
salary
Overloading
Consider a musical instrument like Harmonium, Piano, Drum kit which produces
sound. For Harmonium we need to press some keys and buttons, for Drum
sound is produced either directly with players hand or by using drum stick.
In above example function name is Sound; it takes parameter list like keys,
button or players hand, drum stick.
Overloading is the mechanism having same method name with different
parameter list:
● Scope - in same class
● Signature - different for each method overloaded
● Return type & access modifiers does not matter.
Overriding
● Scope - in different class i.e. can be done in derived class.
● Signature -method name is name with same parameter list as well as
return type.
● Return type must be same.
● Modifiers new, virtual, static, abstract cannot modify method in
derived class.
Why Method Overloaing is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method
because there may occur ambiguity.
Abstraction Encapsulation
Abstraction is a feature of OOPs that hides Encapsulation is also a feature of OOPs. It
the unnecessary detail but shows the hides the code and data into a single entity
essential information. or unit so that the data can be protected
from the outside world.
It solves an issue at the design level. Encapsulation solves an issue
at implementation level.
It focuses on the external lookout. It focuses on internal working.
It can be implemented using abstract It can be implemented by using the access
classes and interfaces. modifiers (private, public, protected).
It is the process of gaining information. It is the process of containing the
information.
In abstraction, we use abstract We use the getters and setters methods to
classes and interfaces to hide the code hide the data.
complexities.
The objects are encapsulated that helps to The object need not to abstract that result
perform abstraction. in encapsulation.
What is programming paradigm?
Programming paradigm are the way to classify programming language based on their
paradigm.
S. On the Procedural Programming Object-oriented programming
n basis of
o.
1. Definition It is a programming language that Object-oriented programming is a
is derived from structure computer programming design
programming and based upon the philosophy or methodology that
concept of calling procedures. It organizes/ models software
follows a step-by-step approach design around data or objects
in order to break down a task into rather than functions and logic.
a set of variables and routines via
a sequence of instructions.
2. Security It is less secure than OOPs. Data hiding is possible in
object-oriented programming
due to abstraction. So, it is more
secure than procedural
programming.
3. Approach It follows a top-down approach. It follows a bottom-up approach.
4. Data In procedural programming, data In OOP, objects can move and
movement moves freely within the system communicate with each other via
from one function to another. member functions.
5. Orientation It is It is object-oriented.
structure/procedure-oriented.
6. Access There are no access modifiers in The access modifiers in OOP are
modifiers procedural programming. named as private, public, and
protected.
7. Inheritance Procedural programming does not There is a feature of inheritance in
have the concept of inheritance. object-oriented programming.
8. Code There is no code reusability It offers code reusability by using
reusability present in procedural the feature of inheritance.
programming.
9. Overloading Overloading is not possible in In OOP, there is a concept of
procedural programming. function overloading and operator
overloading.
10. Importance It gives importance to functions It gives importance to data over
over data. functions.
11. Virtual class In procedural programming, there In OOP, there is an appearance of
are no virtual classes. virtual classes in inheritance.
12. Complex It is not appropriate for complex It is appropriate for complex
problems problems. problems.
13. Data hiding There is not any proper way for There is a possibility of data
data hiding. hiding.
14. Program In Procedural programming, a In OOP, a program is divided into
division program is divided into small small parts that are referred to as
programs that are referred to as objects.
functions.
15. Examples Examples of Procedural The examples of object-oriented
programming include C, Fortran, programming are -
Pascal, and VB. .NET, C#, Python, Java, [Link],
and C++.
Structured Programming:
In the process of coding,the lines of code keep multiplying, thus, size of the
software I ncreases. Gradually, it becomes next to impossib le to remember the
flow of [Link] one forgets how software and its underlying programs, files,
procedures are construc ted, i t then becomes very difficult to share, debug, and
modify the program. The solution to this is structured programming. It encourages
the developer to use subroutines and loops instead of using simple jumps in the
code, thereby bringing clarity in the code and improving its efficiency. Structured
programming also helps programmer to reduce coding time and organize
code properly.
There are three aspects of structured programming:
[Link]-down analysis.
[Link] programming.
[Link] coding.
Top-down analysis: A software is always made to perform some rational work.
This rational work is known as problem in the software [Link] I t is very
important that we understand how to solve the [Link] top down analysis,
the problem I s broken down into small pieces where each one has some
significance. Each problem is individually solved and steps are clearly stated about
how to solve the problem.
Modular programming: While programming, the code is broken down into smaller
group of instructions. These groups are known as modules, subprograms, or
subroutines. Modular programming based on the understanding of top down
analysis. It discourages jumps using 'goto' statements in the program, which often
makes the program flow non-traceable. Jumps are prohibited and modular format
is encouraged in structured programming.
Structured coding: In reference with top-down analysis, structured coding
sub-divides the modules into further smaller units of code in the order of their
execution. Structured programming uses control structure,which controls the flow of
the program, whereas structured coding uses control structure to organize its
instructions in definable patterns.
Advantages of Polymorphism
Polymorphism offers the following advantages −
● It helps the programmer to reuse the codes, i.e., classes once written,
tested and implemented can be reused as required. Saves a lot of time.
● Single variable can be used to store multiple data types.
● Easy to debug the codes.
A process of converting one data type to another is known
as Typecasting and Upcasting and Downcasting is the type of object typecasting. In
Java, the object can also be typecasted like the datatypes. Parent and Child objects are
two types of objects. So, there are two types of typecasting possible for an object,
i.e., Parent to Child and Child to Parent or can say Upcasting and Downcasting.
1) Upcasting
Upcasting is a type of object typecasting in which a child object is typecasted to
a parent class object. By using the Upcasting, we can easily access the variables and
methods of the parent class to the child class. Here, we don't access all the variables
and the method. We access only some specified variables and methods of the child
class. Upcasting is also known as Generalization and Widening.
[Link]
1. class Parent{
2. void PrintData() {
3. [Link]("method of parent class");
4. }
5. }
6.
7. class Child extends Parent {
8. void PrintData() {
9. [Link]("method of child class");
10. }
11. }
12. class UpcastingExample{
13. public static void main(String args[]) {
14.
15. Parent obj1 = (Parent) new Child();
16. Parent obj2 = (Parent) new Child();
17. [Link]();
18. [Link]();
19. }
20. }
Output:
2) Downcasting
Upcasting is another type of object typecasting. In Upcasting, we assign a parent class
reference object to the child class. In Java, we cannot assign a parent class reference
object to the child class, but if we perform downcasting, we will not get any
compile-time error. However, when we run it, it throws the "ClassCastException". Now
the point is if downcasting is not possible in Java, then why is it allowed by the
compiler? In Java, some scenarios allow us to perform downcasting. Here, the subclass
object is referred by the parent class.
Below is an example of downcasting in which both the valid and the invalid scenarios
are explained:
[Link]
1. //Parent class
2. class Parent {
3. String name;
4.
5. // A method which prints the data of the parent class
6. void showMessage()
7. {
8. [Link]("Parent method is called");
9. }
10. }
11.
12. // Child class
13. class Child extends Parent {
14. int age;
15.
16. // Performing overriding
17. @Override
18. void showMessage()
19. {
20. [Link]("Child method is called");
21. }
22. }
23.
24. public class Downcasting{
25.
26. public static void main(String[] args)
27. {
28. Parent p = new Child();
29. [Link] = "Shubham";
30.
31. // Performing Downcasting Implicitly
32. //Child c = new Parent(); // it gives compile-time error
33.
34. // Performing Downcasting Explicitly
35. Child c = (Child)p;
36.
37. [Link] = 18;
38. [Link]([Link]);
39. [Link]([Link]);
40. [Link]();
41. }
42. }
Why we need Upcasting and Downcasting?
In Java, we rarely use Upcasting. We use it when we need to develop a code that deals
with only the parent class. Downcasting is used when we need to develop a code that
accesses behaviors of the child class.
Difference between Upcasting and Downcasting
These are the following differences between Upcasting and Downcasting:
[Link] Upcasting Downcasting
1. A child object is typecasted to a parent The reference of the parent class object is
object. passed to the child class.
2. We can perform Upcasting implicitly or Implicitly Downcasting is not possible.
explicitly.
3. In the child class, we can access the The methods and variables of both the
methods and variables of the parent classes(parent and child) can be accessed.
class.
4. We can access some specified methods All the methods and variables of both classes
of the child class. can be accessed by performing downcasting.
5. Parent p = new Parent() Parent p = new Child()
Child c = (Child)p;
In Java, the constructor is similar to the method. The property of the constructor is that
it must have the same name as the class name. It has no return type. We do not require
to call the constructor manually. It automatically invokes implicitly during the
instantiation.
In other words, a constructor is a method that is called at runtime during the object
creation by using the new operator.
Automatic initialization of objects at the time of their declaration.
Multiple ways to initialize objects according to the number of arguments
passes while declaration.
The objects of child class can be initialized by the constructors of base class.
Abstract class Interface
1) Abstract class can have abstract and Interface can have only abstract methods. Since
non-abstract methods. Java 8, it can have default and static methods also.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.
4) Abstract class can provide the implementation Interface can't provide the implementation of
of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.
6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.
7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Association in Java
Association, in general terms, refers to the relationship between any two entities.
Association in java is the relationship that can be established between any two classes.
These relationships can be of four types:
1. One-to-One relation
2. One-to-many relation
3. Many-to-one relation
4. Many-to-many relation
To illustrate, let’s take two classes, Professor class, and Department class. Below are the
type of relationships/associations that can be possible between them
● One professor can only be assigned to work in one department.
This forms a one-to-one association between the two classes.
● One professor can be assigned to work in multiple departments.
This is a one-to-many association between the two classes.
● Multiple professors can be assigned to work in one department.
This forms a many-to-one association between the two classes.
● Multiple professors can be assigned to work in multiple
departments. This is the many-to-many association between the
two classes.
Forms of Association in Java
Before we dive into the forms of Association in java, let us briefly explore the types of
object relationships that can exist in OOPs. There can be two types of relationships in
OOPs:
● IS-A
● HAS-A
1. IS-A (Inheritance)
The IS-A relationship is nothing but Inheritance. The relationships that can be established
between classes using the concept of inheritance are called IS-A relations.
Ex: A parrot is-a Bird. Here Bird is a base class, and Parrot is a derived class, Parrot class
inherits all the properties and attributes & methods (other than those that are private) of
base class Bird, thus establishing inheritance(IS-A) relation between the two classes.
The HAS-A association on the other hand is where the Instance variables of a class refer to
objects of another class. In other words, one class stores the objects of another class as its
instance variables thereby establishing a HAS-A association between the two classes.
2. HAS-A (association)
Note: The example program for the association we have discussed in the above section is a
HAS-A [Link] Department class is storing the objects of Professor class as its
instance variable staff ( the Listwhich is storing a list of Professors class objects). And a
Department class object can access these stored Professor objects to store/retrieve
information from Professor Class, thereby creating an association between the two
classes.
There are two forms of Association that are possible in Java:
a) Aggregation
b) Composition
Aggregation:
Aggregation in java is a form of HAS-A relationship between two classes. It is a relatively
more loosely coupled relation than composition in that, although both classes are
associated with each other, one can exist without the other independently. So Aggregation
in java is also called a weak association. Let us look at a simple aggregation example to
understand this better.
Composition:
Composition in java is a form of relation that is more tightly coupled. Composition in
java is also called Strong association. This association is also known as Belongs-To
association as one class, for all intents and purpose belongs to another class, and
exists because of it. In a Composition association, the classes cannot exist
independent of each other. If the larger class which holds the objects of the smaller
class is removed, it also means logically the smaller class cannot exist.
Difference between association, aggregation, composition
in Java
Association in java is one of the types of relations between classes. It has two forms
Aggregation(HAS-A) and Composition(Belongs-to). Aggregation is a relatively weak
association, whereas Composition is a strong association. Composition can be called a more
restricted form of Aggregation. Aggregation can be called the superset of Composition, since
all Compositions can are Aggregations but, not all Aggregations can be called Composition.
Below are the primary differences between the forms of Association, Composition and
Aggregation in java:
Aggregation Composition
Weak Association Strong Association
One class is dependent on Another Independent
Classes in relation can exist independently
class. The Dependent class cannot exist
Aggregation Composition
independently in the event of the non-existence of an
independent class.
One class has-a relationship with another class Once class belongs-to another class
Code is not that reusable as the association is
Helps with code reusability. Since classes exist dependent. Such Associations once established will
independently, associations can be reassigned create a dependency, and these associations cannot
or new associations created without any be reassigned or new associations like aggregation,
modifications to the existing class. etc cannot be created without changing the existing
class.