Inheritance, Interfaces, and Polymorphism
Method Overriding and Runtime Polymorphism
আপনি একটি free preview lesson দেখছেন।
Lesson Overview
আগের lessons-এ আমরা শিখেছি:
- Child class কীভাবে parent class extend করে
- Parent constructor কীভাবে
super(...)দিয়ে call হয় - Child object কীভাবে parent state এবং behavior inherit করে
এখন inheritance-এর সবচেয়ে গুরুত্বপূর্ণ behavior শিখব: method overriding।
ধরা যাক সব content item-এর estimated learning duration প্রয়োজন।
Video lesson-এর duration সরাসরি video length থেকে পাওয়া যায়।
Article lesson-এর duration reading time থেকে পাওয়া যায়।
Quiz lesson-এর duration question count-এর ওপর depend করতে পারে।
সব content-এর জন্য একই operation:
calculateEstimatedMinutes()
কিন্তু implementation content type অনুযায়ী different।
ContentItem content =
new VideoLesson(...);
System.out.println(
content.calculateEstimatedMinutes()
);
Reference type ContentItem হলেও Java runtime actual VideoLesson implementation execute করতে পারে।
এটিই runtime polymorphism।
এই lesson-এ আমরা শিখব:
- Method overriding কী
@Override- Same signature এবং compatible return type
- Parent reference এবং child object
- Runtime method dispatch
super.method()- Overriding এবং overloading-এর difference
- Static method hiding
- Fields কেন polymorphic নয়
- Private এবং final methods-এর behavior
- Parent contract preserve করার importance
- Weak override কীভাবে hierarchy ভেঙে দেয়
Learning Objectives
এই lesson শেষ করার পর আপনি পারবেন:
- Parent method child class-এ override করতে
@Overridecorrectly ব্যবহার করতে- Runtime method dispatch explain করতে
- Parent reference দিয়ে child-specific implementation execute করতে
super.method()দিয়ে parent implementation reuse করতে- Overriding এবং overloading distinguish করতে
- Static method hiding explain করতে
- Field access এবং method dispatch-এর difference বুঝতে
- Override method-এর access visibility correctly design করতে
- Child behavior parent contract preserve করছে কি না evaluate করতে
What Is Method Overriding?
Child class parent-এর inherited instance method-এর নতুন implementation দিলে তাকে method overriding বলা হয়।
Parent:
public class ContentItem {
public int calculateEstimatedMinutes() {
return 0;
}
}
Child:
public class VideoLesson
extends ContentItem {
private final int durationInMinutes;
@Override
public int calculateEstimatedMinutes() {
return durationInMinutes;
}
}
VideoLesson parent method-এর behavior replace করেছে।
Requirements for Overriding
একটি child method parent method override করতে সাধারণত প্রয়োজন:
- Same method name
- Same parameter list
- Compatible return type
- Compatible access level
- Parent method overridable হতে হবে
Parent:
public int calculateEstimatedMinutes() {
return 0;
}
Child:
@Override
public int calculateEstimatedMinutes() {
return durationInMinutes;
}
Signature same:
calculateEstimatedMinutes()
Return typeও same:
int
The @Override Annotation
Override method-এর আগে লিখুন:
@Override
Example:
@Override
public int calculateEstimatedMinutes() {
return durationInMinutes;
}
@Override compiler-কে বলে:
এই methodটি parent বা interface method override করার কথা।
যদি signature ভুল হয়, compiler error দেয়।
Why @Override Matters
Suppose parent method:
public int calculateEstimatedMinutes() {
return 0;
}
Child accidentally writes:
public int calculateEstimateMinutes() {
return durationInMinutes;
}
Method name slightly different:
calculateEstimatedMinutes
calculateEstimateMinutes
@Override ছাড়া এটি নতুন method হিসেবে compile করতে পারে।
Parent method override হবে না।
With annotation:
@Override
public int calculateEstimateMinutes() {
return durationInMinutes;
}
Compiler error দেবে।
Practical rule:
Override করা প্রতিটি method-এর সঙ্গে
@Overrideব্যবহার করুন।
A Common Parent Method
public class ContentItem {
private final long id;
private final String title;
private boolean published;
public ContentItem(
long id,
String title
) {
if (id <= 0) {
throw new IllegalArgumentException(
"Content ID must be positive."
);
}
if (
title == null
|| title.isBlank()
) {
throw new IllegalArgumentException(
"Content title is required."
);
}
this.id = id;
this.title = title.strip();
this.published = false;
}
public int calculateEstimatedMinutes() {
return 0;
}
public boolean publish() {
if (published) {
return false;
}
published = true;
return true;
}
public long getId() {
return id;
}
public String getTitle() {
return title;
}
public boolean isPublished() {
return published;
}
}
Parent default implementation 0 return করছে।
এটি compile করে, কিন্তু design হিসেবে questionable।
যদি generic ContentItem-এর meaningful duration calculation না থাকে, abstract method stronger হতে পারে।
Abstract classes Lesson 4-এ শেখানো হবে।
এখন overriding behavior বোঝার জন্য concrete method ব্যবহার করছি।
Overriding in VideoLesson
public class VideoLesson
extends ContentItem {
private final String videoUrl;
private final int durationInMinutes;
public VideoLesson(
long id,
String title,
String videoUrl,
int durationInMinutes
) {
super(
id,
title
);
if (
videoUrl == null
|| videoUrl.isBlank()
) {
throw new IllegalArgumentException(
"Video URL is required."
);
}
if (durationInMinutes <= 0) {
throw new IllegalArgumentException(
"Video duration must be positive."
);
}
this.videoUrl =
videoUrl.strip();
this.durationInMinutes =
durationInMinutes;
}
@Override
public int calculateEstimatedMinutes() {
return durationInMinutes;
}
public String getVideoUrl() {
return videoUrl;
}
}
Video duration already known।
তাই estimated learning time:
return durationInMinutes;
Overriding in ArticleLesson
public class ArticleLesson
extends ContentItem {
private final int wordCount;
public ArticleLesson(
long id,
String title,
int wordCount
) {
super(
id,
title
);
if (wordCount <= 0) {
throw new IllegalArgumentException(
"Word count must be positive."
);
}
this.wordCount =
wordCount;
}
@Override
public int calculateEstimatedMinutes() {
int wordsPerMinute = 200;
return Math.max(
1,
wordCount
/ wordsPerMinute
);
}
}
Article estimated duration word count থেকে calculate হচ্ছে।
Overriding in QuizLesson
public class QuizLesson
extends ContentItem {
private final int questionCount;
public QuizLesson(
long id,
String title,
int questionCount
) {
super(
id,
title
);
if (questionCount <= 0) {
throw new IllegalArgumentException(
"Question count must be positive."
);
}
this.questionCount =
questionCount;
}
@Override
public int calculateEstimatedMinutes() {
int minutesPerQuestion = 2;
return questionCount
* minutesPerQuestion;
}
}
Same operation:
calculateEstimatedMinutes()
Different implementation।
Parent Reference, Child Object
ContentItem content =
new VideoLesson(
1L,
"Method Overriding",
"https://cdn.liveklass.io/video/1",
18
);
Compile-time type:
ContentItem
Runtime type:
VideoLesson
Call:
int minutes =
content.calculateEstimatedMinutes();
Which implementation executes?
VideoLesson.calculateEstimatedMinutes()
Result:
18
Java actual runtime object দেখে overridden instance method select করে।
Runtime Method Dispatch
Runtime method dispatch-এর flow:
ContentItem content =
new VideoLesson(...);
Compiler checks:
Does ContentItem declare calculateEstimatedMinutes()?
হ্যাঁ।
তাই call compile হয়।
Runtime checks:
Actual object type কী?
VideoLesson
তারপর most specific override execute হয়।
VideoLesson.calculateEstimatedMinutes()
Dynamic Dispatch
Runtime method selection-কে dynamic method dispatch-ও বলা হয়।
Example:
ContentItem first =
new VideoLesson(
1L,
"Video",
"https://example.com/video",
20
);
ContentItem second =
new ArticleLesson(
2L,
"Article",
1_000
);
ContentItem third =
new QuizLesson(
3L,
"Quiz",
10
);
Calls:
System.out.println(
first.calculateEstimatedMinutes()
);
System.out.println(
second.calculateEstimatedMinutes()
);
System.out.println(
third.calculateEstimatedMinutes()
);
Possible output:
20
5
20
Same method call syntax।
Behavior runtime object type অনুযায়ী selected।
Why Runtime Polymorphism Is Useful
Without polymorphism:
if (contentType.equals("VIDEO")) {
calculateVideoDuration();
} else if (
contentType.equals("ARTICLE")
) {
calculateArticleDuration();
} else if (
contentType.equals("QUIZ")
) {
calculateQuizDuration();
}
Problems:
- Type-specific logic এক জায়গায় জমে
- New content type add করলে condition update করতে হয়
- Caller child implementation details জানে
- Behavior data-এর owner object-এর কাছে থাকে না
With polymorphism:
int minutes =
content.calculateEstimatedMinutes();
Each content type নিজের behavior implement করে।
Polymorphism Is Not Just Different Classes
Polymorphism-এর key point:
একই parent contract-এর মাধ্যমে different runtime implementations ব্যবহার করা।
Example contract:
calculateEstimatedMinutes()
Implementations:
VideoLesson
ArticleLesson
QuizLesson
Caller common type-এর ওপর কাজ করে।
Calling the Parent Implementation with super.method()
Child override method parent implementation reuse করতে পারে।
Parent:
public String createSummary() {
return getTitle();
}
Child:
@Override
public String createSummary() {
return super.createSummary()
+ " — Video lesson";
}
super.createSummary() parent implementation call করে।
Complete super.method() Example
Parent:
public class ContentItem {
private final String title;
public ContentItem(
String title
) {
this.title = title;
}
public String createSummary() {
return "Title: "
+ title;
}
}
Child:
public class VideoLesson
extends ContentItem {
private final int durationInMinutes;
public VideoLesson(
String title,
int durationInMinutes
) {
super(title);
this.durationInMinutes =
durationInMinutes;
}
@Override
public String createSummary() {
return super.createSummary()
+ ", Duration: "
+ durationInMinutes
+ " minutes";
}
}
Output:
Title: Overriding, Duration: 18 minutes
When to Use super.method()
Useful when child:
- Parent behavior preserve করতে চায়
- Parent result extend করতে চায়
- Common validation বা formatting reuse করতে চায়
- Parent algorithm-এর একটি অংশ retain করতে চায়
Avoid blindly calling super.method()।
Ask:
Parent behavior কি child contract-এর জন্য সত্যিই প্রয়োজন?
Replacing vs Extending Parent Behavior
Completely Replace
@Override
public int calculateEstimatedMinutes() {
return durationInMinutes;
}
Parent result ব্যবহার করা হয়নি।
Extend Parent Behavior
@Override
public String createSummary() {
return super.createSummary()
+ ", Type: Video";
}
Parent result reuse করা হয়েছে।
Overriding vs Overloading
দুইটি concept similar মনে হলেও different।
Overriding
- Parent-child relationship প্রয়োজন
- Same method signature
- Runtime polymorphism
- Child parent implementation replace বা extend করে
class ContentItem {
int calculateEstimatedMinutes() {
return 0;
}
}
class VideoLesson
extends ContentItem {
@Override
int calculateEstimatedMinutes() {
return 20;
}
}
Overloading
- Same class বা inherited context-এ same method name
- Different parameter lists
- Compile-time method selection
- Parent-child relationship required নয়
void publish() {
}
void publish(
boolean notifyLearners
) {
}
Overriding vs Overloading Table
| Overriding | Overloading |
|---|---|
| Same signature | Different parameter list |
| Parent-child relationship | Relationship required নয় |
| Runtime selection | Compile-time selection |
| Behavior replacement | Input variation |
@Override ব্যবহার করা হয় | @Override নয় |
An Overloading Mistake
Parent:
public void publish() {
}
Child:
public void publish(
boolean notify
) {
}
এটি override নয়।
এটি overload।
Parent method still exists:
child.publish();
Child overload:
child.publish(true);
@Override লিখলে compiler mistake ধরবে।
Return Type Compatibility
Override method same return type ব্যবহার করতে পারে।
Parent:
public ContentItem copy() {
return this;
}
Child:
@Override
public VideoLesson copy() {
return this;
}
Child more specific return type ব্যবহার করেছে।
এটিকে covariant return type বলা হয়।
Beginner level-এ rule:
Override return type parent return type-এর same বা valid subtype হতে পারে।
Primitive return type freely change করা যায় না।
Invalid:
public int calculateEstimatedMinutes() {
}
Child:
@Override
public long calculateEstimatedMinutes() {
}
Compile হবে না।
Parameter Types Must Match
Parent:
public void updateTitle(
String title
) {
}
Child:
public void updateTitle(
Object title
) {
}
এটি override নয়।
Parameter type different।
এটি overload হতে পারে।
Correct override:
@Override
public void updateTitle(
String title
) {
}
Access Visibility Cannot Be Reduced
Parent:
public void publish() {
}
Child cannot write:
@Override
protected void publish() {
}
Compile হবে না।
Child parent public contract weaker করতে পারে না।
Allowed:
protected → public
package-private → protected or public
But not:
public → protected
public → private
Why Visibility Cannot Be Reduced
Suppose caller has parent reference:
ContentItem content =
new VideoLesson(...);
content.publish();
Parent contract says publish() public।
Child যদি method hidden করে, substitutability break হবে।
Therefore override same বা wider visibility রাখতে হয়।
Checked Exception Rules: Brief Introduction
Override method parent method-এর তুলনায় broader checked exception declare করতে পারে না।
এই course-এ checked exceptions পরে বিস্তারিত শেখানো হবে।
এখন practical point:
Child override parent contract-এর caller obligations unexpectedly বাড়াতে পারবে না।
Runtime exceptions-এর rules different।
Private Methods Are Not Overridden
Parent:
private void validate() {
}
Child:
private void validate() {
}
এগুলো same-looking হলেও overriding নয়।
Parent private method child-এর কাছে visible নয়।
Child method completely separate।
Final Methods Cannot Be Overridden
Parent:
public final long getId() {
return id;
}
Child:
@Override
public long getId() {
return 999L;
}
Compile হবে না।
final parent implementation lock করে।
Constructors Are Not Overridden
Constructors methods-এর মতো inherit বা override হয় না।
Parent constructor:
ContentItem(
long id
)
Child constructor:
VideoLesson(
long id
)
Same parameter থাকলেও overriding নয়।
Each constructor নিজের class initialize করে।
Static Methods Are Hidden, Not Overridden
Parent:
public class ContentItem {
public static String getCategory() {
return "CONTENT";
}
}
Child:
public class VideoLesson
extends ContentItem {
public static String getCategory() {
return "VIDEO";
}
}
এটি overriding নয়।
এটিকে method hiding বলা হয়।
Static Method Selection Uses Reference Type
ContentItem content =
new VideoLesson(...);
System.out.println(
content.getCategory()
);
Possible output:
CONTENT
কারণ static method runtime object নয়, compile-time reference type-এর সঙ্গে resolved হয়।
Preferred access:
ContentItem.getCategory();
VideoLesson.getCategory();
Object reference দিয়ে static call misleading।
Instance vs Static Method Dispatch
Instance Method
content.calculateEstimatedMinutes();
Runtime object type অনুযায়ী override selected।
Static Method
ContentItem.getCategory();
Class বা reference compile-time type অনুযায়ী selected।
Static behavior polymorphic নয়।
Fields Are Not Polymorphic
Parent:
public class ContentItem {
public String type =
"CONTENT";
}
Child:
public class VideoLesson
extends ContentItem {
public String type =
"VIDEO";
}
Usage:
ContentItem content =
new VideoLesson();
System.out.println(
content.type
);
Output:
CONTENT
Field access compile-time reference type-এর ওপর based।
Field Hiding
Child same-name field declare করলে parent field replace করে না।
দুইটি separate fields থাকে।
ContentItem.type
VideoLesson.type
এটিকে field hiding বলা হয়।
This design confusing।
Practical rule:
Parent এবং child classes-এ same-name fields avoid করুন।
Behavior polymorphism-এর জন্য methods ব্যবহার করুন।
Use a Method Instead of a Polymorphic-Looking Field
Avoid:
public String type =
"CONTENT";
Prefer:
public String getContentType() {
return "CONTENT";
}
Child override:
@Override
public String getContentType() {
return "VIDEO";
}
Now runtime polymorphism works।
Runtime Dispatch Through Multiple Levels
Hierarchy:
ContentItem
└── VideoLesson
└── LiveVideoLesson
Suppose all override same method।
ContentItem content =
new LiveVideoLesson(...);
content.calculateEstimatedMinutes();
Java most specific runtime override execute করবে:
LiveVideoLesson implementation
If LiveVideoLesson override না করে, nearest inherited override execute হবে:
VideoLesson implementation
Parent Contract Must Be Preserved
Overriding childকে arbitrary behavior করার permission দেয় না।
Parent contract:
calculateEstimatedMinutes()
returns a non-negative estimate
Bad child:
@Override
public int calculateEstimatedMinutes() {
return -100;
}
Signature correct হলেও semantic contract broken।
Compiler এটি ধরবে না।
Syntactic Correctness vs Behavioral Correctness
Compiler checks:
- Method name
- Parameters
- Return type
- Visibility
- Annotation correctness
Compiler সাধারণত check করে না:
- Result meaningful কি না
- Parent invariant preserved কি না
- Side effects unexpected কি না
- Failure behavior compatible কি না
Design judgment developer-এর responsibility।
Weakening Preconditions
Parent contract:
Any positive question count is accepted.
Child যদি require করে:
Question count must be at least 100.
Parent caller child use করে unexpectedly fail করতে পারে।
Child parent-এর তুলনায় stronger precondition impose করলে substitutability break হতে পারে।
Weakening Postconditions
Parent contract:
publish() returns true only when item becomes published.
Child:
@Override
public boolean publish() {
return true;
}
কিন্তু state change করে না।
Caller contract trust করতে পারবে না।
Unexpected Side Effects
Parent query:
public int calculateEstimatedMinutes() {
}
Child override:
@Override
public int calculateEstimatedMinutes() {
publish();
return durationInMinutes;
}
Caller শুধু duration জানতে চেয়েছিল।
Method secretly publication state change করছে।
এটি surprising এবং parent query contract violate করতে পারে।
Throwing UnsupportedOperationException
Bad hierarchy signal:
@Override
public boolean publish() {
throw new UnsupportedOperationException(
"This content cannot be published."
);
}
যদি parent বলে every ContentItem publishable, child publish support করা উচিত।
না হলে:
- Parent abstraction too broad
- Child wrong hierarchy-তে
- Capability interface প্রয়োজন হতে পারে
Template Behavior with Overriding
Parent common algorithm define করতে পারে এবং specific step child override করতে পারে।
public boolean publish() {
if (isPublished()) {
return false;
}
if (!isReadyForPublication()) {
return false;
}
markPublished();
return true;
}
Child custom readiness:
@Override
protected boolean isReadyForPublication() {
return videoUrl.startsWith(
"https://"
);
}
এটি template-style behavior।
Abstract class lesson-এ refinedভাবে শেখানো হবে।
Avoid Overriding for Every Small Difference
Suppose only difference একটি numeric value:
Video lesson playback speed
Article words per minute
Inheritance possible হলেও configuration field বা composed policy simpler হতে পারে।
Not every variation needs a subclass।
Ask:
- Differenceটি type-defining কি?
- Behavior truly different কি?
- New subclass adding value করছে কি?
- Configuration sufficient কি?
Complete Example
ContentItem.java
public class ContentItem {
private final long id;
private final String title;
private boolean published;
public ContentItem(
long id,
String title
) {
if (id <= 0) {
throw new IllegalArgumentException(
"Content ID must be positive."
);
}
if (
title == null
|| title.isBlank()
) {
throw new IllegalArgumentException(
"Content title is required."
);
}
this.id = id;
this.title = title.strip();
this.published = false;
}
public int calculateEstimatedMinutes() {
return 0;
}
public String getContentType() {
return "CONTENT";
}
public boolean publish() {
if (published) {
return false;
}
published = true;
return true;
}
public final long getId() {
return id;
}
public final String getTitle() {
return title;
}
public final boolean isPublished() {
return published;
}
}
VideoLesson.java
public class VideoLesson
extends ContentItem {
private final String videoUrl;
private final int durationInMinutes;
public VideoLesson(
long id,
String title,
String videoUrl,
int durationInMinutes
) {
super(
id,
title
);
if (
videoUrl == null
|| videoUrl.isBlank()
) {
throw new IllegalArgumentException(
"Video URL is required."
);
}
if (durationInMinutes <= 0) {
throw new IllegalArgumentException(
"Video duration must be positive."
);
}
this.videoUrl =
videoUrl.strip();
this.durationInMinutes =
durationInMinutes;
}
@Override
public int calculateEstimatedMinutes() {
return durationInMinutes;
}
@Override
public String getContentType() {
return "VIDEO";
}
public String getVideoUrl() {
return videoUrl;
}
}
ArticleLesson.java
public class ArticleLesson
extends ContentItem {
private static final int WORDS_PER_MINUTE =
200;
private final int wordCount;
public ArticleLesson(
long id,
String title,
int wordCount
) {
super(
id,
title
);
if (wordCount <= 0) {
throw new IllegalArgumentException(
"Word count must be positive."
);
}
this.wordCount =
wordCount;
}
@Override
public int calculateEstimatedMinutes() {
int estimatedMinutes =
wordCount
/ WORDS_PER_MINUTE;
return Math.max(
1,
estimatedMinutes
);
}
@Override
public String getContentType() {
return "ARTICLE";
}
}
QuizLesson.java
public class QuizLesson
extends ContentItem {
private static final int MINUTES_PER_QUESTION =
2;
private final int questionCount;
public QuizLesson(
long id,
String title,
int questionCount
) {
super(
id,
title
);
if (questionCount <= 0) {
throw new IllegalArgumentException(
"Question count must be positive."
);
}
this.questionCount =
questionCount;
}
@Override
public int calculateEstimatedMinutes() {
return questionCount
* MINUTES_PER_QUESTION;
}
@Override
public String getContentType() {
return "QUIZ";
}
}
Main.java
public class Main {
public static void main(
String[] args
) {
ContentItem video =
new VideoLesson(
1L,
"Method Overriding",
"https://cdn.liveklass.io/videos/overriding",
18
);
ContentItem article =
new ArticleLesson(
2L,
"Runtime Polymorphism",
1_200
);
ContentItem quiz =
new QuizLesson(
3L,
"Overriding Assessment",
10
);
printEstimate(video);
printEstimate(article);
printEstimate(quiz);
}
private static void printEstimate(
ContentItem content
) {
System.out.println(
"Type: "
+ content.getContentType()
);
System.out.println(
"Title: "
+ content.getTitle()
);
System.out.println(
"Estimated time: "
+ content
.calculateEstimatedMinutes()
+ " minutes"
);
System.out.println();
}
}
Possible output:
Type: VIDEO
Title: Method Overriding
Estimated time: 18 minutes
Type: ARTICLE
Title: Runtime Polymorphism
Estimated time: 6 minutes
Type: QUIZ
Title: Overriding Assessment
Estimated time: 20 minutes
printEstimate() কোনো explicit type check করেনি।
Runtime dispatch appropriate child methods execute করেছে।
Engineering Note: Parent Default Implementation or Abstract Method?
Current parent:
public int calculateEstimatedMinutes() {
return 0;
}
Potential problem:
0meaningful estimate নাও হতে পারে- Child override করতে ভুলে যেতে পারে
- Invalid default silently production-এ যেতে পারে
Stronger design:
public abstract int calculateEstimatedMinutes();
তাহলে every concrete child implementation দিতে বাধ্য।
Abstract class এবং abstract method পরবর্তী lesson-এ শেখানো হবে।
Common Mistakes
Forgetting @Override
Code কাজ করতে পারে, কিন্তু signature mistake detect করা কঠিন হয়।
Changing Parameter Types
calculateEstimatedMinutes(
int speed
)
Parent no-argument method override করে না।
Reducing Visibility
Parent public method child protected বা private করতে পারে না।
Using Static Methods for Polymorphic Behavior
Static methods runtime dispatch support করে না।
Hiding Fields
Same-name parent এবং child fields confusing compile-time behavior তৈরি করে।
Calling Child-Specific Methods Through Parent Type
ContentItem content =
new VideoLesson(...);
content.getVideoUrl();
Parent contract-এ method নেই।
Breaking Parent Contract
Correct signature alone behavioral substitutability guarantee করে না।
Throwing UnsupportedOperationException for Core Parent Behavior
Hierarchy বা parent abstraction ভুল হতে পারে।
Adding Unexpected Side Effects to Queries
Calculation method state mutate করা উচিত নয়, unless contract explicitly বলে।
Overriding Everything
Inherited behavior correct হলে override করার প্রয়োজন নেই।
Practice Exercises
Exercise 1: Override Quiz Duration
Create:
QuizLesson
Override:
calculateEstimatedMinutes()
Rule:
3 minutes per question
Exercise 2: Override Content Type
Parent:
public String getContentType() {
return "CONTENT";
}
Implement child values:
VIDEO
ARTICLE
QUIZ
Exercise 3: Use Parent Reference
Create:
ContentItem content =
new ArticleLesson(
1L,
"Polymorphism",
800
);
Predict which implementation executes:
content.calculateEstimatedMinutes();
Exercise 4: Identify Override or Overload
A
class Parent {
void process(
String value
) {
}
}
class Child
extends Parent {
void process(
String value
) {
}
}
B
class Child
extends Parent {
void process(
int value
) {
}
}
Classify each।
Exercise 5: Fix Visibility
Parent:
public void publish() {
}
Child:
@Override
private void publish() {
}
Fix the code and explain the rule।
Exercise 6: Replace a Field with a Method
Refactor:
class ContentItem {
public String type =
"CONTENT";
}
class VideoLesson
extends ContentItem {
public String type =
"VIDEO";
}
Use polymorphic method instead।
Exercise 7: Evaluate Contract Safety
Parent contract:
calculateEstimatedMinutes() returns zero or a positive value.
Review:
@Override
public int calculateEstimatedMinutes() {
return -1;
}
Explain why compiler accepts it but design is wrong।
Predict the Result
Question 1
ContentItem content =
new VideoLesson(
1L,
"Overriding",
"https://example.com/video",
15
);
System.out.println(
content.calculateEstimatedMinutes()
);
Question 2
Parent:
public String getType() {
return "CONTENT";
}
Child:
@Override
public String getType() {
return "VIDEO";
}
ContentItem content =
new VideoLesson(...);
System.out.println(
content.getType()
);
Question 3
Parent:
public static String getType() {
return "CONTENT";
}
Child:
public static String getType() {
return "VIDEO";
}
ContentItem content =
new VideoLesson(...);
System.out.println(
content.getType()
);
Question 4
Parent:
public String type =
"CONTENT";
Child:
public String type =
"VIDEO";
ContentItem content =
new VideoLesson(...);
System.out.println(
content.type
);
Question 5
Parent:
public final void publish() {
}
Can child override it?
Predict the Result Answers
Answer 1
15
Runtime object VideoLesson, তাই child override execute হবে।
Answer 2
VIDEO
Instance method runtime dispatch ব্যবহার করে।
Answer 3
CONTENT
Static method runtime polymorphic নয়। Compile-time reference type অনুযায়ী selected।
Answer 4
CONTENT
Fields runtime polymorphic নয়।
Answer 5
না।
Final method override করা যায় না।
Knowledge Check
Question 1
Method overriding কী?
Question 2
Override method-এর parameter list কী হতে হয়?
Question 3
@Override কেন useful?
Question 4
Runtime method dispatch কী?
Question 5
Parent reference child override execute করতে পারে কি?
Question 6
super.method() কী করে?
Question 7
Overriding এবং overloading-এর difference কী?
Question 8
Child কি public parent method protected করতে পারে?
Question 9
Private method override হয় কি?
Question 10
Final method override হয় কি?
Question 11
Static methods override হয় কি?
Question 12
Fields polymorphic কি?
Question 13
Same-name child field parent field replace করে কি?
Question 14
Correct signature কি correct behavioral contract guarantee করে?
Question 15
Unsupported parent behavior child-এ exception দিয়ে disable করা কী indicate করতে পারে?
Knowledge Check Answers
Answer 1
Child class parent instance method-এর same signatureসহ নতুন implementation দিলে।
Answer 2
Parent method-এর সঙ্গে same হতে হয়।
Answer 3
Compiler confirm করে method সত্যিই override করছে এবং signature mistakes ধরতে সাহায্য করে।
Answer 4
Runtime actual object type অনুযায়ী most specific overridden instance method select করা।
Answer 5
হ্যাঁ।
Answer 6
Parent implementation call করে।
Answer 7
Overriding same signature দিয়ে inherited behavior replace করে এবং runtime-selected। Overloading different parameters দিয়ে method variation তৈরি করে এবং compile-time-selected।
Answer 8
না। Visibility reduce করা যায় না।
Answer 9
না। Parent private method child-এর কাছে visible নয়।
Answer 10
না।
Answer 11
না। Static methods hidden হয়।
Answer 12
না। Field access compile-time reference type-এর ওপর depend করে।
Answer 13
না। Separate field hide করে।
Answer 14
না। Semantic rules এবং invariants developerকে preserve করতে হয়।
Answer 15
Parent abstraction too broad অথবা child hierarchy-তে incorrectly placed হতে পারে।
Lesson Summary
এই lesson-এ আমরা শিখেছি:
- Method overriding childকে parent instance method specialize করতে দেয়
- Override method same name এবং parameter list ব্যবহার করে
@Overridecompiler-assisted correctness দেয়- Compatible return type required
- Child method visibility reduce করতে পারে না
- Parent reference child object hold করতে পারে
- Overridden instance method runtime object type অনুযায়ী selected হয়
- Runtime method selection dynamic dispatch নামে পরিচিত
super.method()parent implementation call করে- Child parent behavior replace বা extend করতে পারে
- Overriding এবং overloading different concepts
- Overloading compile-time-selected
- Overriding runtime-selected
- Constructors override হয় না
- Private methods override হয় না
- Final methods override করা যায় না
- Static methods override নয়, hide হয়
- Static method selection compile-time type-based
- Fields polymorphic নয়
- Same-name child field parent field hide করে
- Behavior polymorphism-এর জন্য methods ব্যবহার করা উচিত
- Most specific runtime override execute হয়
- Compiler syntactic contract check করে, domain correctness নয়
- Child parent preconditions unnecessarily stronger করা উচিত নয়
- Child parent guarantees দুর্বল করা উচিত নয়
- Query override unexpected mutation করা উচিত নয়
- Core parent behavior unsupported হলে hierarchy reconsider করা উচিত
- Default parent implementation invalid হলে abstract method stronger হতে পারে
Next Lesson
পরবর্তী lesson:
Abstract Classes and Interfaces
আমরা শিখব:
- Abstract class কেন প্রয়োজন
- Abstract method
- Concrete shared behavior
- Abstract class instantiate করা যায় না কেন
- Interface contract
implements- Multiple interfaces
- Abstract class বনাম interface
- Shared state বনাম shared capability
- Unnecessary abstraction avoid করা