0% found this document useful (0 votes)
5 views11 pages

Java Notes Polymorphism Final Aggregation

The document provides notes on key Java concepts including Polymorphism, the Final keyword, and Aggregation/Composition. It explains Polymorphism as the ability of a subclass to have its own behavior while allowing parent-type references to point to child objects, and discusses the implications of the Final keyword in restricting variable, method, and class modifications. Additionally, it distinguishes between Aggregation and Composition as two types of HAS-A relationships in object-oriented programming, highlighting their differences in dependency and existence of objects.

Uploaded by

shivanandu.dev
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views11 pages

Java Notes Polymorphism Final Aggregation

The document provides notes on key Java concepts including Polymorphism, the Final keyword, and Aggregation/Composition. It explains Polymorphism as the ability of a subclass to have its own behavior while allowing parent-type references to point to child objects, and discusses the implications of the Final keyword in restricting variable, method, and class modifications. Additionally, it distinguishes between Aggregation and Composition as two types of HAS-A relationships in object-oriented programming, highlighting their differences in dependency and existence of objects.

Uploaded by

shivanandu.dev
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Notes | TAP Academy — Polymorphism, Final Keyword & Aggregation/Composition

JAVA NOTES
Polymorphism | Final Keyword | Aggregation & Composition

1. POLYMORPHISM
Polymorphism is derived from two Greek words: 'poly' (many) and 'morphs' (forms). So polymorphism
means MANY FORMS.

Key Concepts
• A subclass has its own behaviour from its parent class — not the other way around.
• A parent class cannot have the behaviour of its subclass.
• Method Overloading is known as false polymorphism or compile-time polymorphism.
• Method Overriding achieves true (runtime) polymorphism.

Loose Coupling & Polymorphism


Creating parent-type references to child objects is called LOOSE COUPLING,
through which polymorphism is achieved.

• Using a parent type reference, we can invoke only inherited and overridden methods.
• Tight coupling: only a child class's reference can access behaviours of that child class.
• Limitation: Using a parent type reference, we CANNOT directly access the specialized methods of
the child class.

Example 1 — Basic Polymorphism (Different References)


Three subclasses extend Plane and each overrides the fly() method:

class Plane {
void fly() {
[Link]("Plane is flying");
}
}

class CargoPlane extends Plane {


void fly() {
[Link]("CargoPlane is flying at low height");
}
}

class PassengerPlane extends Plane {


void fly() {
[Link]("PassengerPlane is flying at medium height");
}

Page 1
Java Notes | TAP Academy — Polymorphism, Final Keyword & Aggregation/Composition

class FighterPlane extends Plane {


void fly() {
[Link]("FighterPlane is flying at great height");
}
}

Achieving Polymorphism using a single parent-type reference:


public class Demo {
public static void main(String[] args) {
CargoPlane cp = new CargoPlane();
PassengerPlane pp = new PassengerPlane();
FighterPlane fp = new FighterPlane();

Plane ref; // single parent-type reference


ref = cp;
[Link](); // calls CargoPlane's fly()

ref = pp;
[Link](); // calls PassengerPlane's fly()

ref = fp;
[Link](); // calls FighterPlane's fly()
}
}

Output:
CargoPlane is flying at low height
PassengerPlane is flying at medium height
FighterPlane is flying at great height

Example 2 — Downcasting to Access Specialized Methods


Each child class has specialized methods (e.g., carryCargo(), carryPassenger(), carryWeapons()).
These CANNOT be accessed via a parent-type reference directly.

Without Downcasting — Causes Error:


Plane ref;
ref = cp;
[Link]();
[Link](); // ERROR: method undefined for type Plane

Error Output:
Exception in thread 'main' [Link]: Unresolved compilation problems:
The method carryCargo() is undefined for the type Plane
The method carryPassenger() is undefined for the type Plane
The method carryWeapons() is undefined for the type Plane

Page 2
Java Notes | TAP Academy — Polymorphism, Final Keyword & Aggregation/Composition

With Downcasting — Works Correctly:


Downcasting: explicitly converting a parent-type reference to a child type reference,
so specialized methods can be accessed. Use with caution — can cause runtime
errors if the reference doesn't actually point to the child object.

Plane ref;
ref = cp;
[Link]();
((CargoPlane)ref).carryCargo(); // Downcasting

ref = pp;
[Link]();
((PassengerPlane)ref).carryPassenger();

ref = fp;
[Link]();
((FighterPlane)ref).carryWeapons();

Output:
CargoPlane is flying at low height
CargoPlane is carrying cargo
PassengerPlane is flying at medium height
PassengerPlane is carrying passengers
FighterPlane is flying at great height
FighterPlane is carrying weapons

Advantages of Polymorphism
• Code Reusability — same method name used across multiple child classes.
• Flexibility — parent reference can point to any child object.
• Reduction in Complexity — Airport example shows one method handling all plane types.

Airport Example — Achieving Code Flexibility:


class Airport {
void permit(Plane ref) { // accepts any Plane subclass
[Link]();
[Link]();
[Link]();
}
}

public class Demo {


public static void main(String[] args) {
CargoPlane cp = new CargoPlane();
PassengerPlane pp = new PassengerPlane();
FighterPlane fp = new FighterPlane();
Airport a = new Airport();
[Link](cp); // polymorphism in action

Page 3
Java Notes | TAP Academy — Polymorphism, Final Keyword & Aggregation/Composition

[Link](pp);
[Link](fp);
}
}

In the above code, the advantages of polymorphism are fully achieved — code
reduction and flexibility.

Rules of Method Overriding


• Name and return type of the method CANNOT be changed.
• Access modifiers can only be increased (widened): default → protected → public.
• Static methods CANNOT be overridden. Redefining the same static method in a child class is
called Method Hiding.
• Final methods CANNOT be overridden.

Method Summary in a Child Class:


Method Type Description Example (Windows extends
Os)
Inherited Received from parent, body shutdown()
unchanged
Overridden Received from parent, body boot()
changed
Specialized New method defined only in playGame()
child class

Page 4
Java Notes | TAP Academy — Polymorphism, Final Keyword & Aggregation/Composition

2. FINAL KEYWORD
The final keyword in Java is used to restrict the user. It can be applied in three contexts:

Context Effect Restriction


final variable Value becomes constant Cannot reassign the value
final method Method is locked Cannot override the method
final class Class is locked Cannot extend/inherit the class

2.1 Final Variable


• Once declared as final, the value of the variable cannot be changed — it becomes a constant.
• A final variable with no initial value is called an Uninitialized Final Variable.
• An uninitialized final variable can be initialized only in the constructor.

Example:
class Test {
final int a = 100; // final variable
}

public class Demo {


public static void main(String[] args) {
Test t1 = new Test();
[Link](t1.a); // prints 100
t1.a = 200; // ERROR: cannot assign value to final
variable
}
}

Error Output:
error: cannot assign a value to final variable a
t1.a = 200;
^

2.2 Final Method


• If a method is declared final, it CANNOT be overridden by child classes.

Example:
class Test1 {
final void fun() {
[Link]("Inside parent class method");

Page 5
Java Notes | TAP Academy — Polymorphism, Final Keyword & Aggregation/Composition

}
}

class Test2 extends Test1 {


void fun() { // ERROR: cannot override final method
[Link]("Inside child class overridden method");
}
}

Error Output:
error: fun() in Test2 cannot override fun() in Test1
void fun(){
^
overridden method is final

2.3 Final Class


• If a class is declared final, it CANNOT be extended (inherited).

Example:
final class Test1 {
final void fun() {
[Link]("Inside parent class method");
}
}

class Test2 extends Test1 { // ERROR: cannot inherit from final Test1
void fun() {
[Link]("Inside child class overridden method");
}
}

Error Output:
error: cannot inherit from final Test1
class Test2 extends Test1 {
^
1 error

Page 6
Java Notes | TAP Academy — Polymorphism, Final Keyword & Aggregation/Composition

3. AGGREGATION AND COMPOSITION


Aggregation and Composition are two types of HAS-A relationships in object-oriented programming.

Aggregation Composition

Relationship HAS-A (loose bound) HAS-A (tight bound)


Dependency Objects can exist independently Component cannot exist without
parent
Example Mobile HAS-A Charger (charger can Mobile HAS-A OS (OS cannot exist
exist alone) without mobile)
UML Empty/Open diamond Filled/Solid diamond
Symbol

Relationship Types Summary


• IS-A relationship is handled using Inheritance (extends).
• HAS-A relationship is handled using Aggregation and Composition.
• Aggregation is a LOOSE BOUND has-a relationship.
• Composition is a TIGHT BOUND has-a relationship.

Example 1 — Mobile, OS, and Charger


A phone contains an OS (composition) and a Charger (aggregation). • Charger
HAS-A relationship with Mobile: AGGREGATION (loosely bound) — charger can
exist without phone. • OS HAS-A relationship with Mobile: COMPOSITION (tightly
bound) — OS cannot exist without phone.

OS Class (Composition part):


class OS {
private String name;
private int size;

public OS(String name, int size) {


super();
[Link] = name;
[Link] = size;
}

public String getName() { return name; }


public int getSize() { return size; }
}

Page 7
Java Notes | TAP Academy — Polymorphism, Final Keyword & Aggregation/Composition
Charger Class (Aggregation part):
class Charger {
private String brand;
private float voltage;

public Charger(String brand, float voltage) {


super();
[Link] = brand;
[Link] = voltage;
}

public String getBrand() { return brand; }


public float getVoltage() { return voltage; }
}

Mobile Class:
class Mobile {
OS os = new OS("Android", 512); // Composition — OS created inside
Mobile

// Aggregation — Charger is passed from outside


void hasA(Charger c) {
[Link]([Link]());
[Link]([Link]());
}
}

Demo Class:
public class Demo {
public static void main(String[] args) {
Charger c = new Charger("Samsung", 24.5f);
Mobile m = new Mobile();
[Link]([Link]()); // Android
[Link]([Link]()); // 512
[Link](c); // Samsung, 24.5

m = null; // Mobile is destroyed


// OS is also destroyed (Composition)
// But Charger c still exists (Aggregation)

[Link]([Link]()); // Samsung — still accessible


[Link]([Link]()); // 24.5
}
}

Output:
Android
512
Samsung
24.5
Samsung
24.5

Page 8
Java Notes | TAP Academy — Polymorphism, Final Keyword & Aggregation/Composition

Example 2 — Student, Heart, Brain, Bike, Book


Student has TIGHT BOUND (Composition) with Heart and Brain — these cannot
exist independently. Student has LOOSE BOUND (Aggregation) with Bike and Book
— these can exist independently.

class Heart { private int weight; private int bpm; ... }


class Brain { private int weight; private String colour; ... }
class Bike { private String brand; private int mileage; ... }
class Book { private String name; private String author; ... }

class Student {
Heart h = new Heart(289, 72); // Composition
Brain b = new Brain(1400, "grey"); // Composition

void hasA(Book book) {


[Link]([Link]());
[Link]([Link]());
}
void hasA(Bike bike) {
[Link]([Link]());
[Link]([Link]());
}
}

public class Demo {


public static void main(String[] args) {
Student s = new Student();
Bike bike = new Bike("Duke", 35);
Book book = new Book("Java", "JG");

[Link]([Link]()); // 289
[Link]([Link]()); // 72
[Link]([Link]()); // 1400
[Link]([Link]()); // grey
[Link](bike);
[Link](book);

s = null; // Student destroyed => Heart & Brain destroyed


(Composition)
// Bike & Book still exist (Aggregation)

[Link]([Link]()); // Duke
[Link]([Link]()); // 35
[Link]([Link]()); // Java
[Link]([Link]()); // JG
}
}

Output:
289
72
1400
grey

Page 9
Java Notes | TAP Academy — Polymorphism, Final Keyword & Aggregation/Composition

Duke
35
Java
JG
Duke
35
Java
JG

Page 10
Java Notes | TAP Academy — Polymorphism, Final Keyword & Aggregation/Composition

4. QUICK REVISION SUMMARY


Polymorphism
• Means 'many forms' — one reference, many behaviours.
• Achieved through method overriding (runtime polymorphism).
• Parent-type reference pointing to child object = Loose Coupling.
• Can only call inherited/overridden methods via parent reference.
• Use downcasting to access specialized methods of child class.
• Advantages: Code reusability, Flexibility, Reduced complexity.

Final Keyword
• final variable → value is constant, cannot be reassigned.
• final method → cannot be overridden in child classes.
• final class → cannot be extended/inherited.
• Uninitialized final variable can only be initialized in a constructor.

Aggregation vs Composition
• Both are HAS-A relationships in OOP.
• Aggregation (loose bound): objects exist independently.
• Composition (tight bound): child cannot exist without parent.
• IS-A → Inheritance. HAS-A → Aggregation or Composition.

Remember: IS-A = extends (Inheritance) | HAS-A = Aggregation / Composition


Loose coupling = Aggregation = objects independent Tight coupling = Composition =
objects dependent

Page 11

You might also like