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

OOPS Concept Part 2 Revision - Class

Uploaded by

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

OOPS Concept Part 2 Revision - Class

Uploaded by

RANGOS
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Subject-OOPS CONCEPTS

Object Oriented Programming Concepts:


 Abstraction, Association
 Encapsulation,
Composition,
Polymorphism,
Aggregation,
 Inheritance,
Message Passing
Object Oriented Programming Concepts
In Java, an object is more than just a runtime entity; it’s the embodiment of a class. These objects mirror real-world entities,
complete with both state and behavior. Think of a ‘Car’ object based on a ‘Car’ class. It possesses attributes like color,
brand, and speed, along with behaviors like ‘accelerate’ and ‘brake’. This is where Java OOP concepts come to life.

A class in Java serves as a blueprint for creating objects. It bundles data (attributes) and behavior (methods) that define the
object. Consider a ‘Car’ class; it defines attributes like color and methods like ‘accelerate()’. Essentially, a class is a template
that characterizes what can be instantiated as an object, exemplifying OOPs concepts.

Abstraction in Java involves concealing complexity while exposing only the essential aspects. It’s realized through abstract
classes and interfaces. For instance, a ‘Vehicle’ interface declares a ‘move()’ method, but the actual implementation is left to
classes like ‘Car’ or ‘Bike’. This focus on “what an object does” rather than “how it does it” is a core OOPs concept in Java.

Inheritance is a mechanism where a new class (subclass) derives attributes and methods from an existing class
(superclass). This fosters code reusability and establishes a hierarchical relationship between classes. For example, an
‘ElectricCar’ class can inherit traits from the ‘Car’ class, showcasing the practicality of Java OOPs concepts.

Polymorphism allows Java methods and objects to assume multiple forms. It finds common use in method overloading
(same method name, different parameters) and method overriding (same method name and parameters in subclass as in
parent class). Consider a ‘draw()’ method implemented differently in ‘Circle’, ‘Square’, and ‘Triangle’ classes as a prime
example of polymorphism in Java.

Encapsulation is a pivotal OOPs principle in Java. It entails bundling data (attributes) and code (methods) into a cohesive
unit. Moreover, it limits direct access to an object’s components, preventing inadvertent interference. Techniques like using
private variables and offering public getter and setter methods exemplify Java OOPs concepts put into practice.
Polymorphism refers to many forms, or it is a process that performs a single action
in different ways. It occurs when we have many classes related to each other by
inheritance.

Polymorphism is of two different types, i.e., compile-time polymorphism and runtime


polymorphism. One of the examples of Compile time polymorphism is that when we overload a
static method in java. Run time polymorphism also called a dynamic method dispatch is a
method in which a call to an overridden method is resolved at run time rather than compile time.
In this method, the overridden method is always called through the reference variable. By using
method overloading and method overriding, we can perform polymorphism. Generally, the
concept of polymorphism is often expressed as one interface, and multiple methods. This
reduces complexity by allowing the same interface to be used as a general class of action.
Static polymorphism
The process of binding the overloaded method within
object at compile time is known as Static
polymorphism due to static polymorphism utilization
of resources (main memory space) is poor because
for each and every overloaded method a memory
space is created at compile time when it binds with an
object. In C++ environment the above problem can be
solve by using dynamic polymorphism by
implementing with virtual and pure virtual function so
most of the C++ developer in real worlds follows only
dynamic polymorphism.

Dynamic polymorphism
In dynamic polymorphism method of the program
binds with an object at runtime the advantage of
dynamic polymorphism is allocating the memory
space for the method (either for overloaded method or
for override method) at run time.
In this diagram the sum method which is present in
BC class is called original form and the sum()
method which are present in DC1 and DC2 are
called overridden form hence Sum() method is
originally available in only one form and it is further
implemented in multiple forms. Hence Sum()
method is one of the polymorphism method.
Question 3:What is the primary mechanism that allows runtime polymorphism in Java?
a) Method Overloading
b) Method Overriding
c) Static Binding
d) Final Methods
e) Abstract Classes
Question 3:What is the primary mechanism that allows runtime polymorphism in Java?
a) Method Overloading
b) Method Overriding
c) Static Binding
d) Final Methods
e) Abstract Classes
Correct Answer: b) Method Overriding

Explanation:b) Method Overriding is correct because runtime polymorphism in Java is achieved through method
overriding. When a subclass provides its own implementation of a method that is already defined in its superclass,
and an instance of the subclass is used with a superclass reference, the overridden method in the subclass is
invoked at runtime. This dynamic behavior is the essence of runtime polymorphism.

Why the other options are incorrect:


a) Method Overloading: This deals with compile-time polymorphism, where multiple methods with the same name
but different parameters are defined in the same class. The method to be invoked is determined at compile time, not
at runtime.
c) Static Binding: This refers to binding that occurs at compile time (e.g., method overloading). It is the opposite of
dynamic binding, which is required for runtime polymorphism.
d) Final Methods: A final method cannot be overridden, so it cannot participate in runtime polymorphism.
e) Abstract Classes: While abstract classes are important in object-oriented programming, they do not directly
enable runtime polymorphism. They provide a template for subclasses, but the actual polymorphism occurs when a
method is overridden.
Question 4:In a polymorphic system, which of the following best describes the behavior when
a method is overridden in a subclass and called on a superclass reference?

A) The method in the superclass will always be called.


B) The method in the subclass will superclass type.
E) The method in the subclass will be called if it's not markedalways be called.
C) The method in the subclass is called only if the reference type matches the subclass type.
D) The method in the superclass is called if the reference type is the as final in the superclass.
Question 4:In a polymorphic system, which of the following best describes the behavior when a method is
overridden in a subclass and called on a superclass reference?
A) The method in the superclass will always be called.
B) The method in the subclass will always be called.
C) The method in the subclass is called only if the reference type matches the subclass type.
D) The method in the superclass is called if the reference type is the superclass type.
E) The method in the subclass will be called if it's not marked as final in the superclass.

Correct Answer: B) The method in the subclass will always be called.

Explanation: In object-oriented programming, when a method is overridden in a subclass and a superclass


reference is used to call the method, the method of the actual object (subclass) is executed, not the
method defined in the superclass. This is due to runtime polymorphism (or dynamic method dispatch),
where the method to be called is determined at runtime based on the object's type, not the reference type.

Option A is incorrect because the method in the superclass will not be called unless explicitly called using
super.method().
Option C is incorrect because the reference type doesn’t need to match; the actual object's type matters.
Option D is incorrect as it applies to the compile-time method resolution, but polymorphism is resolved at
runtime.
Option E is incorrect because the final keyword prevents overriding, but the subclass method will still be called
if the method isn't final.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal {


@Override
void sound() {
System.out.println("Cat meows");
}
}

public class Main {


public static void main(String[] args) {
Animal myAnimal = new Dog(); // Superclass reference to a subclass object
myAnimal.sound(); // Calls the Dog's sound() method
}
}
class Animal {
void sound() {
System.out.println("Animal makes a sound");
} Superclass Reference, Subclass Object: In the code above, the myAnimal
} variable is declared as type Animal, but it is assigned an object of type Dog. This
is a key concept in polymorphism where a superclass reference can point to an
class Dog extends Animal { object of any subclass.
@Override
void sound() { Method Overriding: Both Dog and Cat classes override the sound() method of
the Animal class. This means that the subclass provides its own implementation
System.out.println("Dog barks");
of the sound() method.
}
} Runtime Polymorphism: When myAnimal.sound() is called, the actual object
type (Dog) determines which method is executed, not the reference type
class Cat extends Animal { (Animal). So, even though myAnimal is of type Animal, the method from the Dog
@Override class is invoked at runtime.
void sound() {
Output: The output will be "Dog barks" because the actual object is of type
System.out.println("Cat meows");
Dog, and the Dog class overrides the sound() method of Animal.
}
} Compile Time: The reference type (Animal) determines which methods are
available to call.
public class Main { Runtime: The actual object type (Dog) determines which method is executed.
public static void main(String[] args) {
Animal myAnimal = new Dog(); // Superclass reference to a subclass object
myAnimal.sound(); // Calls the Dog's sound() method
}
}
Method Overloading:
In the case of Method overloading, the compiler determines which Method to call based on the types and number of arguments
provided. This information is available at compile time, allowing the compiler to select the correct Method to be invoked.

#include <iostream>

class Solution {
public:
void func(int x) { std::cout << "value of x is " << x << std::endl; }

void func(double x) { std::cout << "value of x is " << x <<


std::endl; }

void func(int x, int y) {


std::cout << "value of x and y is " << x << ", " << y << std::endl;
}
};

int main() {
Solution obj1;
obj1.func(7);
obj1.func(9.132);
obj1.func(85, 64);
return 0;
}
Operator overloading is a programming language feature that allows the same operator
to be used with different meanings or behaviors depending on the types of operands
involved. It allows developers to redefine the behavior of operators for custom types or
classes.

“Hamza” + “Khan”, where “+” is used for concatenating two strings.


12 + 34, but here “+” is used for adding two integers.

In many programming languages, certain


operators such as addition (+), subtraction
(-), multiplication (*), and equality (==)
have predefined behavior for built-in types.
However, with operator overloading, you
can extend these operators to work with
user-defined types in a way that makes
sense for those types.
Question 5:Which of the following is the correct reason why method overloading fails in this scenario in
Java?

class Calculator {
public void add(int a, long b) {
System.out.println("int-long");
}

public void add(long a, int b) {


System.out.println("long-int");
}

public static void main(String[] args) {


Calculator calc = new Calculator();
calc.add(10, 10);
}
}
a) Ambiguous method call
b) Method overriding error
c) Compile-time error due to method signature
d) Java allows only one overloaded method in a class
e) Runtime exception
Question 5:Which of the following is the correct reason why method overloading fails in this scenario in Java?

class Calculator {
public void add(int a, long b) {
System.out.println("int-long");
}

public void add(long a, int b) {


System.out.println("long-int");
}

public static void main(String[] args) {


Calculator calc = new Calculator();
calc.add(10, 10);
}}
a) Ambiguous method call
b) Method overriding error
c) Compile-time error due to method signature
d) Java allows only one overloaded method in a class
e) Runtime exception
Correct Answer: a) Ambiguous method call
Explanation:
a) Ambiguous method call is correct because both add(int, long) and add(long, int) methods could be valid for the call add(10, 10). The compiler
cannot determine which method to call since 10 can be treated as both an int and long, leading to ambiguity.
Why the other options are incorrect:
b) Method overriding error: This error would occur in case of inheritance and overriding, but here the issue is with overloading.
c) Compile-time error due to method signature: Both methods have valid signatures, so no compilation error occurs due to signature.
d) Java allows only one overloaded method in a class: Java allows multiple overloaded methods, provided they differ by parameter type, number,
or order.
e) Runtime exception: This error occurs at compile time due to ambiguity, so no runtime exception is involved.
Question 6:What will happen when the following overloaded methods are invoked?
class Display {
public void show(int a, double b) {
System.out.println("int-double");
}

public void show(double a, int b) {


System.out.println("double-int");
}

public void show(float a, float b) {


System.out.println("float-float");
}

public static void main(String[] args) {


Display obj = new Display();
obj.show(10, 10.5f);
}
}
a) int-double
b) double-int
c) float-float
d) Ambiguous method call
e) Compilation failure
Question 6:What will happen when the following overloaded methods are
invoked?
class Display {
public void show(int a, double b) {
System.out.println("int-double");
}

public void show(double a, int b) {


Correct Answer: a) int-double
System.out.println("double-int");
Explanation:a) int-double is correct because when obj.show(10, 10.5f) is called, Java
} automatically promotes 10.5f (float) to 10.5 (double), which matches the method show(int,
double).
public void show(float a, float b) { Why the other options are incorrect:
System.out.println("float-float"); b) double-int: The method show(double, int) would not match because the first argument is int,
} and it needs to be matched with the int-double method instead.
c) float-float: This method is not invoked because the first argument 10 is an int, not a float. Java
does not implicitly convert int to float.
public static void main(String[] args) {
d) Ambiguous method call: There is no ambiguity here since only one valid method show(int,
Display obj = new Display(); double) matches the call.
obj.show(10, 10.5f); e) Compilation failure: The code compiles correctly since all the methods have valid signatures.
}
}
a) int-double
b) double-int
c) float-float
d) Ambiguous method call
e) Compilation failure
Dynamic Binding

Dynamic binding always says create an object of base class but do not
create the object of derived classes. Dynamic binding principal is always used
for executing polymorphic applications.

The process of binding appropriate versions (overridden method) of derived


classes which are inherited from base class with base class object is known
as dynamic binding.

Advantages of dynamic binding along with polymorphism with method


overriding are.

1) Less memory space


2) Less execution time
3) More performance

Advantages of Dynamic Polymorphism


1) Dynamic Polymorphism allows Java to support overriding of methods
which is central for run-time polymorphism.
2) It allows a class to specify methods that will be common to all of its
derivatives while allowing subclasses to define the specific
implementation of some or all of those methods.
3) It also allows subclasses to add its specific methods subclasses to define
the specific implementation of same.
Question 7:What will be the output of the following Java program, and why?
class Parent {
void display() {
System.out.println("Parent display");
}
}

class Child extends Parent {


@Override
void display() {
System.out.println("Child display");
}
}

public class Main {


public static void main(String[] args) {
Parent obj = new Child();
obj.display();
}
}
a) Parent display
b) Child display
c) Compilation error due to method overriding
d) Compilation error due to type mismatch
e) Runtime exception
Question 7:What will be the output of the following Java program, and why?
class Parent {
void display() {
System.out.println("Parent display");
}
} Correct Answer: b) Child display
Explanation:
class Child extends Parent { b) Child display is correct because the reference variable obj is of type
@Override Parent, but it refers to an object of the Child class. In Java, dynamic
void display() { binding ensures that the method of the actual object (in this case, Child) is
System.out.println("Child display"); called, not the method of the reference type (Parent).
} Why the other options are incorrect:
} a) Parent display: This would occur in static binding, where the reference
type determines the method call, but Java uses dynamic binding for non-
public class Main { static methods.
public static void main(String[] args) { c) Compilation error due to method overriding: Method overriding is
Parent obj = new Child(); allowed in Java, so there is no compilation error.
obj.display(); d) Compilation error due to type mismatch: There is no type mismatch
} here. A parent class reference can point to a subclass object.
} e) Runtime exception: No runtime exception will occur because the
a) Parent display method invocation and class structure are correct.
b) Child display
c) Compilation error due to method overriding
d) Compilation error due to type mismatch
e) Runtime exception
Question 8: Which of the following statements about dynamic binding is correct
in Java?
a) Dynamic binding happens at compile-time.
b) Dynamic binding is only applicable to static methods.
c) Dynamic binding applies to method calls where the method is resolved at runtime
based on the actual object type.
d) Dynamic binding does not support method overriding.
e) Dynamic binding can be used for instance variables.
Question 8:
Which of the following statements about dynamic binding is correct in Java?
a) Dynamic binding happens at compile-time.
b) Dynamic binding is only applicable to static methods.
c) Dynamic binding applies to method calls where the method is resolved at runtime based on the actual object type.
d) Dynamic binding does not support method overriding.
e) Dynamic binding can be used for instance variables.

Correct Answer: c) Dynamic binding applies to method calls where the method is resolved at runtime based on
the actual object type.

Explanation:
c) Dynamic binding applies to method calls where the method is resolved at runtime based on the actual object
type is correct. In Java, dynamic binding occurs when a method call is made on an object, and the method that gets
executed is determined at runtime based on the actual class of the object, not the reference type.
Why the other options are incorrect:
a) Dynamic binding happens at compile-time: This is false because dynamic binding happens at runtime, not compile-
time.
b) Dynamic binding is only applicable to static methods: Static methods are resolved at compile-time (static binding),
not runtime.
d) Dynamic binding does not support method overriding: Dynamic binding is specifically tied to method overriding,
where subclass methods override parent methods.
e) Dynamic binding can be used for instance variables: Instance variables are resolved at compile-time based on the
reference type, not at runtime, so dynamic binding is not applicable to variables.
Encapsulation is one of the concepts in OOPs concepts; it is the
process that binds together the data and code into a single unit and
keeps both from being safe from outside interference and misuse. In
this process, the data is hidden from other classes and can be
accessed only through the current class’s methods. Hence, it is also
known as data hiding. Encapsulation acts as a protective wrapper that
prevents the code and data from being accessed by outsiders. These
are controlled through a well-defined interface.

Encapsulation is achieved by declaring the variables as private and


providing public setter and getter methods to modify and view the
variable values. In encapsulation, the fields of a class are made read-only
or write-only. This method also improves reusability. Encapsulated code
is also easy to test for unit testing.
Question 9:Which of the following best represents the concept of encapsulation in object-
oriented programming?
a) Hiding the internal state of an object and requiring all interactions to be performed through an
object's methods.
b) Allowing the direct modification of an object’s data members.
c) Using inheritance to share methods between classes.
d) Overloading methods to provide multiple ways of performing an operation.
e) Implementing multiple interfaces to achieve polymorphism.
Question 9:
Which of the following best represents the concept of encapsulation in object-oriented programming?
a) Hiding the internal state of an object and requiring all interactions to be performed through an object's methods.
b) Allowing the direct modification of an object’s data members.
c) Using inheritance to share methods between classes.
d) Overloading methods to provide multiple ways of performing an operation.
e) Implementing multiple interfaces to achieve polymorphism.

Correct Answer: a) Hiding the internal state of an object and requiring all interactions to be performed through an object's
methods.
Explanation:
a) Hiding the internal state of an object and requiring all interactions to be performed through an object's methods is the correct
definition of encapsulation. It ensures that the internal workings of an object are hidden from outside interference, and data can only be
accessed or modified through well-defined methods.
Why the other options are incorrect:
b) Allowing the direct modification of an object’s data members: This contradicts the principle of encapsulation. Direct modification
of data violates data hiding.
c) Using inheritance to share methods between classes: This is related to inheritance, not encapsulation. Encapsulation focuses on
data hiding, not sharing methods.
d) Overloading methods to provide multiple ways of performing an operation: Method overloading is a feature of polymorphism, not
encapsulation.
e) Implementing multiple interfaces to achieve polymorphism: This relates to polymorphism, not encapsulation.
Question 10:What is a primary benefit of encapsulation in object-oriented
programming?
a) It increases code readability by allowing all member variables to be public.
b) It improves security by restricting direct access to the object's data members.
c) It enhances performance by allowing faster access to member variables.
d) It simplifies inheritance by making all variables accessible to subclasses.
e) It allows the programmer to bypass data validation checks for faster
development.
Question 10:What is a primary benefit of encapsulation in object-oriented programming?
a) It increases code readability by allowing all member variables to be public.
b) It improves security by restricting direct access to the object's data members.
c) It enhances performance by allowing faster access to member variables.
d) It simplifies inheritance by making all variables accessible to subclasses.
e) It allows the programmer to bypass data validation checks for faster development.
Correct Answer: b) It improves security by restricting direct access to the object's data members.
Explanation:
b) It improves security by restricting direct access to the object's data members is correct because
encapsulation provides control over how data is accessed or modified, reducing the risk of unintended or
malicious interference.
Why the other options are incorrect:
a) It increases code readability by allowing all member variables to be public: Making member
variables public defeats the purpose of encapsulation and doesn't necessarily improve readability.
c) It enhances performance by allowing faster access to member variables: Encapsulation may
slightly reduce performance due to method calls, but it prioritizes security and proper data handling over
speed.
d) It simplifies inheritance by making all variables accessible to subclasses: Encapsulation often
restricts access to variables, and while inheritance can access protected members, encapsulation enforces
control over public access.
e) It allows the programmer to bypass data validation checks for faster development: Encapsulation
encourages the use of methods that include data validation, which cannot be bypassed if data is properly
encapsulated.
Abstraction is the art of building things in such a way that the people using
them should never need to care about how they work, but instead should
only care about the outcomes they offer and certain inputs they require.
Abstractions are everywhere. A simple light switch is an easy example. It
requires minimum effort to learn what a wall mounted button does - if you
switch it on, which is achieved by positioning the button in a certain way -
the light goes on. If positioned the other way, it goes off. If one never
studies basic electric cirtcuits, they might never know what goes inside the
switch. But the most important thing is that it does not matter - knowing or
not knowing how a switch works does not affect its output and that is the
absolute beauty of abstraction.
There are also abstract classes and abstract
methods.
An abstract class is a type of class that declares one
or more abstract methods. An abstract method is a
method that has a method definition but not
implementation. Once we have modelled our object
using data abstraction, the same sets of data can
also be used in different applications—abstract
classes, generic types of behaviors and object-
oriented programming hierarchy. Abstract methods
are used when two or more subclasses do the same
task in different ways and through different
implementations. An abstract class can have both
methods, i.e., abstract methods and regular methods.
In general, when we think about Object-oriented programming, it
is everything around the “Objects” and their relationships.

Object of one class communicates with the objects of other class


using the methods in it. This kind of communication or a relation is
called as “Association”. It is a generic term used to represent
when a class uses the functionalities provided by another class.

Aggregation and Composition are just two different types of


Association. Both follows the concept of “one class owning the
object of other class”. The only difference is their weak and
strong nature as we mentioned in the below table.
Question 11:Which of the following best demonstrates the principle of abstraction in object-
oriented programming?
a) Defining detailed internal working mechanisms for all objects in the system.
b) Hiding complex implementation details and exposing only necessary functionalities to the user.
c) Allowing direct access to an object's data members and methods.
d) Using multiple classes to represent specific attributes of a real-world entity.
e) Overriding methods in the subclass to change the behavior of a superclass method.
Question 11:Which of the following best demonstrates the principle of abstraction in
object-oriented programming?
a) Defining detailed internal working mechanisms for all objects in the system.
b) Hiding complex implementation details and exposing only necessary functionalities to the user.
c) Allowing direct access to an object's data members and methods.
d) Using multiple classes to represent specific attributes of a real-world entity.
e) Overriding methods in the subclass to change the behavior of a superclass method.
Correct Answer: b) Hiding complex implementation details and exposing only necessary
functionalities to the user.
Explanation:
b) Hiding complex implementation details and exposing only necessary functionalities to the user is
the correct answer as abstraction focuses on simplifying complex systems by only exposing what is
necessary. This principle allows users to interact with a system without needing to know its internal workings.
Why the other options are incorrect:
a) Defining detailed internal working mechanisms for all objects in the system: This contradicts the
principle of abstraction, which aims to hide complexity, not expose it.
c) Allowing direct access to an object's data members and methods: This violates encapsulation and is
not related to abstraction, which focuses on hiding implementation details.
d) Using multiple classes to represent specific attributes of a real-world entity: While related to OOP,
this concept is more about modeling and design than abstraction.
e) Overriding methods in the subclass to change the behavior of a superclass method: This refers to
polymorphism, specifically method overriding, rather than abstraction.
Question 12:What is one primary advantage of using abstraction in software design?
a) It enhances performance by reducing the number of method calls.
b) It enables easier maintenance and future extensions of the codebase.
c) It allows unrestricted access to an object's internal state.
d) It promotes the reuse of code through inheritance and interfaces.
e) It ensures all objects in a system expose every method they use internally.
Question 12:What is one primary advantage of using abstraction in software design?
a) It enhances performance by reducing the number of method calls.
b) It enables easier maintenance and future extensions of the codebase.
c) It allows unrestricted access to an object's internal state.
d) It promotes the reuse of code through inheritance and interfaces.
e) It ensures all objects in a system expose every method they use internally.
Correct Answer: b) It enables easier maintenance and future extensions of the codebase.
Explanation:
b) It enables easier maintenance and future extensions of the codebase is the correct answer because
abstraction hides unnecessary details, allowing developers to focus on the broader system and make changes
more easily without affecting other parts of the codebase.
Why the other options are incorrect:
a) It enhances performance by reducing the number of method calls: Abstraction does not inherently reduce
method calls or improve performance. Its purpose is to simplify the complexity of the system.
c) It allows unrestricted access to an object's internal state: This violates encapsulation, which, along with
abstraction, prevents direct access to an object's internal details.
d) It promotes the reuse of code through inheritance and interfaces: While abstraction can involve the use of
interfaces, code reuse is more associated with inheritance and polymorphism than abstraction.
e) It ensures all objects in a system expose every method they use internally: Abstraction does the opposite
by hiding unnecessary details, ensuring that only relevant methods are exposed to the user.
Association:-Association is a relationship between two objects. It’s denoted by
“has-a” relationship. In this relationship all objects 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:-Aggregation is a another type of specialised form of Association


where all objects have their own lifecycle, but there is ownership and child
objects can not belong to another parent object. Let’s take an example of
Department and teacher. A single teacher can not belong to multiple
departments, but if we delete the department teacher object will not be
destroyed. We can think about it as a “has-a” relationship.

Composition:-Composition is again specialised form of Aggregation and we


can call this as a “death” relationship. It is a strong type of Aggregation. Child
object does not have its lifecycle and if parent object is deleted, all child objects
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 can not belong to two different houses. If we delete the
house – room will automatically be deleted. 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 be deleted. Let’s take another example of
relationship between Car and Moter, Moter is a vital part of Car, if you remove
moter then Car become useless.
Question 13:Which of the following statements best describes the relationship between objects in
an aggregation?
a) An object cannot exist without the existence of another object it is aggregated with.
b) Objects are strongly bound to each other and are dependent on one another for their lifecycle.
c) Aggregation implies a "has-a" relationship where the parts can exist independently of the whole.
d) Objects in aggregation cannot belong to more than one object at the same time.
e) Aggregation is a specialized form of composition where the child object is created only within the parent
class.
Question 13:Which of the following statements best describes the relationship between objects in
an aggregation?
a) An object cannot exist without the existence of another object it is aggregated with.
b) Objects are strongly bound to each other and are dependent on one another for their lifecycle.
c) Aggregation implies a "has-a" relationship where the parts can exist independently of the whole.
d) Objects in aggregation cannot belong to more than one object at the same time.
e) Aggregation is a specialized form of composition where the child object is created only within the parent
class.

Correct Answer: c) Aggregation implies a "has-a" relationship where the parts can exist
independently of the whole.
Explanation:
c) Aggregation implies a "has-a" relationship where the parts can exist independently of the whole
is the correct answer because, in aggregation, one object can be part of another, but they maintain their
own lifecycles. For example, a library and books: the books can exist independently of the library.
Why the other options are incorrect:
a) An object cannot exist without the existence of another object it is aggregated with: This describes
composition, not aggregation. In aggregation, the objects can exist independently.
b) Objects are strongly bound to each other and are dependent on one another for their lifecycle:
This is also a description of composition, where objects are tightly coupled.
d) Objects in aggregation cannot belong to more than one object at the same time: In aggregation,
objects can belong to more than one entity simultaneously. For example, the same person can be
associated with multiple departments in an organization.
e) Aggregation is a specialized form of composition where the child object is created only within the
parent class: This is a description of composition, where the parent creates and owns the child object.
Question 14:
In a composition relationship, which of the following is true?
a) The child object can exist independently of the parent object.
b) The child object is shared between multiple parent objects.
c) The child object's lifecycle is managed by the parent object and it is destroyed when the parent object is
destroyed.
d) The relationship between parent and child objects is weak, and they can exist independently of one another.
e) Composition implies that the child object will never be destroyed, regardless of the parent object's lifecycle.
Question 14:
In a composition relationship, which of the following is true?
a) The child object can exist independently of the parent object.
b) The child object is shared between multiple parent objects.
c) The child object's lifecycle is managed by the parent object and it is destroyed when the parent object is
destroyed.
d) The relationship between parent and child objects is weak, and they can exist independently of one another.
e) Composition implies that the child object will never be destroyed, regardless of the parent object's lifecycle.
Correct Answer: c) The child object's lifecycle is managed by the parent object and it is destroyed when
the parent object is destroyed.
Explanation:
c) The child object's lifecycle is managed by the parent object and it is destroyed when the parent object
is destroyed is the correct answer because composition defines a strong relationship where the parent and child
objects are tightly bound, and the child cannot exist without the parent.
Why the other options are incorrect:
a) The child object can exist independently of the parent object: This describes aggregation, not composition.
In composition, the child cannot exist without the parent.
b) The child object is shared between multiple parent objects: This is incorrect. In composition, the child
object belongs exclusively to one parent, unlike in aggregation where sharing is possible.
d) The relationship between parent and child objects is weak, and they can exist independently of one
another: This statement describes association, not composition, where the relationship is weak and objects can
exist independently.
e) Composition implies that the child object will never be destroyed, regardless of the parent object's
lifecycle: This is incorrect because in composition, when the parent is destroyed, the child is also destroyed,
meaning their lifecycles are closely tied.
In Java, message passing refers to the process of communication
between objects. In an object-oriented programming paradigm like
Java, objects interact with each other by calling methods, passing
messages that trigger behaviors or actions. These messages typically
contain the necessary data (arguments) required to perform a certain
task, and this interaction allows for modular, reusable, and well-
encapsulated code.
Key Points of Message Passing in Java:
Objects as Communicators: Objects in Java communicate by invoking
methods on other objects. This process involves one object sending a
message (method call) to another object.
Method Invocation: The message sent from one object to another is
represented as a method call. The object that receives the method call
processes the message, often returning a result.
Arguments in Message Passing: When invoking a method, the
sender can pass arguments (message parameters) to the receiver.
These parameters provide the receiver with the necessary information
to process the message.
Dynamic Binding: In cases where the actual method to be executed is
determined at runtime (for example, if an object reference points to a
subclass object), Java uses dynamic method dispatch to resolve the
method that needs to be executed.
Happy Learning!!!
You can ask your doubts, if any, through email to
[email protected].

You might also like