Inheritance, Polymorphism, Algorithms & Integrated Project
Master advanced Object-Oriented Programming concepts including inheritance hierarchies, runtime polymorphism, classic algorithmic strategies (Greedy, DP, Divide & Conquer), and build a complete Student Management System.
A.1 What is Inheritance? ▼
Inheritance lets a new class reuse the fields and methods of an existing class. The existing class is the parent (superclass / base class); the new class is the child (subclass / derived class).
Parent and Child Classes
// Parent class class Person { String name; void displayName() { System.out.println(name); } } // Child class inherits from Person class Student extends Person { int marks; }
Class Diagram
Using Inherited Members
public class Main { public static void main(String[] args) { Student s = new Student(); s.name = "Kamal"; // inherited field s.marks = 80; // own field s.displayName(); // inherited method System.out.println(s.marks); } }
80
A.2 Terminology & Key Rules ▼
| Term | Meaning | Example |
|---|---|---|
| Parent / Superclass | The class being inherited from | Person |
| Child / Subclass | The class that inherits | Student |
| extends | Keyword that creates the inheritance link | class Student extends Person |
| Inherited members | Fields/methods received from parent | name, displayName() |
| Overriding | Child provides own version of inherited method | Dog.sound() |
| super | Reference to parent part of object | super(name) |
| Is-a | Relationship justifying inheritance | Student is a Person |
- A class can extend only one parent class (single inheritance).
- Inheritance can be multi-level: Person → Student → GraduateStudent.
- Every class secretly extends the built-in
Objectclass. - Don't use inheritance just to reuse code. Use it only when the is-a test is true.
A.3 Inherited Members & What a Child Can Add ▼
A child object contains the parent's fields plus its own. The child may also add new methods.
class Person { String name; int age; void displayName() { System.out.println(name); } } class Student extends Person { int marks; // new field boolean isPass() { // new method return marks >= 40; } } // Student object has: name, age, marks // Methods: displayName(), isPass()
A.4 The super Keyword
▼
super refers to the parent class part of the current object. Two main uses:
Use 1: Call parent constructor
super(...) calls the parent constructor. Must be the first statement in the child constructor.
Use 2: Call parent method
super.method() calls the parent's version of a method that the child has overridden.
Example – Calling Parent Constructor
class Person { String name; Person(String name) { this.name = name; System.out.println("Person constructor"); } } class Student extends Person { int marks; Student(String name, int marks) { super(name); // MUST be first this.marks = marks; System.out.println("Student constructor"); } } // new Student("Kamal", 80); // Output: // Person constructor // Student constructor
super(name) passes the value up so the parent can initialize name.Example – Calling Overridden Parent Method
class Student extends Person { int marks = 80; @Override void display() { super.display(); // run Person's version first System.out.println("Marks: " + marks); // then add extra } }
A.5 Constructor Inheritance Rules ▼
super(...)must be the first statement in the child constructor.- If you don't write it, the compiler inserts
super();automatically. - If the parent has only a parameterised constructor, the child must call
super(arguments)explicitly — otherwise a compile error occurs. - Object creation order: parent constructor body runs before child constructor body.
class Person { String name; Person(String name) { // only parameterised this.name = name; } } class Student extends Person { int marks; Student(int marks) { // ❌ ERROR: compiler tried super() but it doesn't exist this.marks = marks; } } // ✅ FIX: class Student2 extends Person { int marks; Student2(String name, int marks) { super(name); // explicit call, first line this.marks = marks; } }
A.6 Member Accessibility: private, protected, public ▼
Access modifiers control who can see and use a class member. They support encapsulation (hiding data inside the class and exposing only what is necessary).
| Modifier | Same Class | Same Package | Subclass | Everywhere |
|---|---|---|---|---|
private | ✅ | ❌ | ❌ | ❌ |
| (default) | ✅ | ✅ | ❌ | ❌ |
protected | ✅ | ✅ | ✅ | ❌ |
public | ✅ | ✅ | ✅ | ✅ |
private and provide public getters/setters. This is the core of encapsulation.
A.7 Method Overriding vs Overloading ▼
Overriding means a subclass provides its own implementation of an inherited method, with the same name, parameters, and compatible return type. Use @Override to let the compiler check.
| Aspect | Overloading | Overriding |
|---|---|---|
| Location | Same class | Subclass |
| Signature | Same name, different parameters | Same name AND parameters |
| Resolution | Compile time | Run time |
| Example | add(int,int) and add(double,double) | Dog.sound() replaces Animal.sound() |
final, static, and private methods cannot be overridden.A.8 Polymorphism – "Many Forms" ▼
Polymorphism means the same method call can produce different behaviour depending on the actual object. It combines inheritance + method overriding + a parent-type reference.
Classic Example
class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Bark"); } } class Cat extends Animal { @Override void sound() { System.out.println("Meow"); } } // Using polymorphism Animal a; a = new Dog(); a.sound(); // Bark a = new Cat(); a.sound(); // Meow
Polymorphism with an Array
Animal[] zoo = { new Dog(), new Cat(), new Animal(), new Dog() };
for (Animal x : zoo) {
x.sound(); // one line, different behaviour per object
}
// Output: Bark, Meow, Animal sound, Bark
A.9 Runtime Polymorphism (Dynamic Method Dispatch) ▼
The JVM decides at run time (not compile time) which overridden method to execute — based on the actual object type, not the reference type.
- Reference type decides which methods you can call (compile-time check).
- Object type decides which overridden method runs (run-time decision).
- To call a child-only method through a parent reference, use
instanceofthen cast.
Safe Downcasting with instanceof
Animal a = new Dog(); if (a instanceof Dog) { Dog d = (Dog) a; // downcast d.fetch(); // OK: fetch() is Dog-only }
Algorithm Strategies Overview ▼
An algorithm is a finite, step-by-step method for solving a problem. Four strategies appear repeatedly in computer science:
| Strategy | Idea | Seen In |
|---|---|---|
| Brute Force | Try every possibility | String matching |
| Greedy | Take the best-looking choice now, never reconsider | Coins, Huffman, Activity Selection, SJF |
| Dynamic Programming | Solve sub-problems once, reuse answers | 0/1 Knapsack |
| Divide & Conquer | Split, solve parts, combine | Binary Search, Fast Power |
B.1 String Matching ▼
Finding whether a pattern occurs inside a text, and where. This powers search boxes, find-and-replace, and spell checkers.
Built-in String Methods
| Method | Purpose |
|---|---|
text.equals(other) | Are two strings identical? |
text.equalsIgnoreCase() | Same, ignoring case |
text.contains(p) | Does text contain p anywhere? |
text.indexOf(p) | Position of first match, or -1 |
startsWith / endsWith | Match at start/end |
charAt(i) | Character at index i |
equals(), never == (which compares memory references, not content).Brute Force Implementation
static int find(String text, String pattern) { for (int i = 0; i <= text.length() - pattern.length(); i++) { int j = 0; while (j < pattern.length() && text.charAt(i + j) == pattern.charAt(j)) { j++; } if (j == pattern.length()) return i; } return -1; }
B.2 Counting Coins (Greedy Approach) ▼
Problem: Make a given amount using the fewest coins.
Greedy: Always take the largest coin that still fits, subtract it, repeat.
Example: Amount = 37, Coins = 25, 10, 5, 1
static void countCoins(int amount, int[] coins) { int totalCoins = 0; for (int coin : coins) { int howMany = amount / coin; if (howMany > 0) { System.out.println(howMany + " x " + coin); totalCoins += howMany; amount = amount % coin; } } System.out.println("Total coins = " + totalCoins); }
B.3 Knapsack Problem (0/1 vs Fractional) ▼
Problem: A thief has a bag with limited capacity. Each item has weight and value. Goal: maximize total value without exceeding capacity.
| Aspect | 0/1 Knapsack | Fractional Knapsack |
|---|---|---|
| Rule | Take item whole or not at all | May take a fraction of an item |
| Method | Dynamic Programming | Greedy by value/weight ratio |
| Real-life | Laptops, boxes, tasks | Grain, liquids, sand |
Fractional Knapsack (Greedy)
static double fractional(int[] wt, int[] val, int capacity) { // Sort by value/weight ratio (highest first) // Take items fully until bag is full // Take fraction of last item that fits double total = 0; int remaining = capacity; for (int i : sortedIndexes) { if (wt[i] <= remaining) { total += val[i]; remaining -= wt[i]; } else { total += val[i] * (double) remaining / wt[i]; break; } } return total; }
dp[i][w] = best value using first i items with capacity w.B.4 Huffman Coding (Lossless Compression) ▼
A lossless data compression method that gives short bit codes to frequent characters and long codes to rare ones. No code is the beginning of another code (prefix code).
Example: "ABRACADABRA"
| Char | Frequency | Code | Bits used |
|---|---|---|---|
| A | 5 | 0 | 5 × 1 = 5 |
| B | 2 | 10 | 2 × 2 = 4 |
| R | 2 | 110 | 2 × 3 = 6 |
| C | 1 | 1110 | 1 × 4 = 4 |
| D | 1 | 1111 | 1 × 4 = 4 |
| Total | 11 | — | 23 bits |
B.5 Activity Selection (Greedy) ▼
Given activities with start/finish times, choose the maximum number of non-overlapping activities.
Example
| Activity | Start | Finish |
|---|---|---|
| A | 1 | 3 |
| B | 2 | 5 |
| C | 4 | 7 |
| D | 6 | 8 |
// Already sorted by finish time System.out.println("Selected: " + name[0]); // A int last = 0; for (int i = 1; i < n; i++) { if (start[i] >= finish[last]) { System.out.println("Selected: " + name[i]); // C last = i; } } // Output: Selected: A, Selected: C
B.6 Scheduling Strategies ▼
Scheduling decides which task runs when, given limited resources (CPUs, rooms, people).
| Strategy | Rule | Notes |
|---|---|---|
| FCFS | Run in arrival order | Simple & fair; one long task delays everything |
| SJF | Shortest task first | Gives lowest average waiting time |
| Priority | Highest priority first | Low priority may starve (aging fixes this) |
| Round Robin | Time slice per task in turn | Used by time-sharing OS |
| EDF | Nearest deadline first | Used in real-time systems |
Example: FCFS vs SJF
| Strategy | Order | Waiting times | Average |
|---|---|---|---|
| FCFS | P1, P2, P3 | 0, 6, 14 | 6.67 |
| SJF | P3, P1, P2 | 0, 3, 9 | 4.00 |
Complete Student Management System ▼
This project combines inheritance, polymorphism, arrays, searching, sorting, methods, and loops into one real-world application.
System Architecture
Person.java (Parent Class)
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void displayInfo() { System.out.println("Name: " + name + ", Age: " + age); } }
Student.java (Child Class)
public class Student extends Person { private int studentId; private int[] marks; public Student(int id, String name, int age, int[] marks) { super(name, age); this.studentId = id; this.marks = marks; } public int calculateTotal() { int total = 0; for (int m : marks) total += m; return total; } public double calculateAverage() { return (double) calculateTotal() / marks.length; } public String findGrade() { double avg = calculateAverage(); if (avg >= 75) return "A"; else if (avg >= 65) return "B"; else if (avg >= 55) return "C"; else if (avg >= 40) return "D"; else return "F"; } @Override public void displayInfo() { super.displayInfo(); System.out.println(" Student ID: " + studentId + ", Grade: " + findGrade()); } }
Menu Operations Implemented
1. Add Student
Read from keyboard, store in Student[] array.
2. Display All
Formatted table of all students.
3. Class Average
Average of all students' averages.
4. Highest Total
Find top scorer.
5. Search by ID
Linear search implementation.
6. Sort by Total
Bubble sort on Student objects.
7. Pass/Fail
Display pass status of each student.
8. Polymorphism Demo
Person[] with Student + Teacher + Person.
Polymorphism in Action
Person[] people = {
new Student(201, "Ruwan", 18, new int[]{60,70,80}),
new Teacher("Mr. Silva", 40, "Java"),
new Person("Visitor", 30)
};
for (Person p : people) {
p.displayInfo(); // Each object runs ITS OWN version!
}
super, encapsulation with private fields, arrays of objects, linear search, bubble sort, and runtime polymorphism.Quick Revision Checklist ▼
🧬 Inheritance
extends creates is-a relationship. Single parent only. Children inherit fields/methods.
⬆️ super
super(...) must be first line of child constructor. super.method() calls parent version.
🔒 Access
private = same class only. protected = subclasses + package. public = everywhere.
🔄 Override vs Overload
Override = same signature in subclass. Overload = same name, different parameters.
🎭 Polymorphism
Parent reference + child object. Real object's method runs at runtime.
🔍 String Matching
equals(), contains(), indexOf(), or brute-force character comparison.
🪙 Greedy
Coins, fractional knapsack, activity selection, Huffman, SJF. 0/1 needs DP.
🌳 Huffman
Merge two lowest frequencies. Left=0, right=1. Frequent chars get short codes.
Practice Questions (Click to reveal hints) ▼
1. Create Vehicle with speed and Car extends Vehicle with doors. Use super in constructor. ▼
super(speed) as first line of Car constructor. Car constructor: Car(int speed, int doors) { super(speed); this.doors = doors; }2. Why can Student not access private String name of Person directly? ▼
private fields are hidden from subclasses. Access via a public getter: public String getName() { return name; }3. Create Shape with area() and subclasses Circle, Rectangle. Use polymorphism. ▼
Shape[] shapes = {new Circle(5), new Rectangle(4,6)}; Loop with for (Shape s : shapes) s.area(); — each runs its own area()!4. Difference between overloading and overriding (with examples). ▼
add(int,int) and add(double,double) in same class. Overriding: Dog.sound() replaces Animal.sound() in subclass.5. Make change for 63 using coins 25, 10, 5, 1. Show where greedy fails. ▼
6. Capacity 10; items (w,v): (5,10),(4,40),(6,30),(3,50). Solve fractional. ▼
7. Build Huffman tree for AABBBCCCC. Compute total bits. ▼
8. Activities (start,finish): (1,4),(3,5),(0,6),(5,7),(8,9),(5,9). Select max compatible set. ▼
9. Add a method to the project that prints only failed students. ▼
for (int i = 0; i < count; i++) if (!students[i].isPass()) students[i].displayStudent();Online ICT Classes in Sri Lanka – O/L, A/L, Cambridge, Edexcel, Python, Web Development & Digital Marketing
Island-wide online classes and home-visit classes in English, Sinhala (සිංහල) and Tamil (தமிழ்) – for school students, university students, BIT / BSc / IT final-year project students, beginners and business owners.
💬 WhatsApp Us Now ▶ Watch Free TutorialsWhat is ITClassSL? ITClassSL is a Sri Lankan ICT training service offering online and home-visit classes for G.C.E. O/L ICT, G.C.E. A/L ICT, Cambridge IGCSE / A Level, Pearson Edexcel, Python, Java, PHP & MySQL, web design, Microsoft Office, university and BIT final-year project guidance, and digital marketing. Classes run in English, Sinhala and Tamil, as individual or group sessions, anywhere in Sri Lanka. Contact: WhatsApp +94 72 962 2034 · itclasssl@gmail.com.
🚀 Learn Today. Build Tomorrow.
Looking for ICT classes in Sri Lanka, online ICT tuition, A/L ICT online class, computer classes near me or BIT project help? We provide practical, exam-focused and career-focused IT training with past papers, model papers, step-by-step coding and one-to-one support.
💡 Our ICT Training & Services in Sri Lanka
🏫 School ICT Classes (Grade 1 – 13)
Online and home-visit ICT lessons for Sri Lankan school students.
- G.C.E. O/L ICT (සාමාන්ය පෙළ ICT / சாதாரண தர ICT)
- G.C.E. A/L ICT (උසස් පෙළ ICT / உயர்தர ICT)
- GIT (General Information Technology)
- Term test papers, past papers & revision
🤖 Programming & AI
Learn to code from zero to project level.
- Python, C, Java, PHP, JavaScript
- HTML, CSS, jQuery & AJAX
- AI & machine-learning basics
- Problem solving & algorithms
🎓 University & Final-Year Project Guidance
Technical guidance for BIT, BSc, IT and ICT students.
- BIT / UCSC / UoM final-year projects
- PHP & MySQL, Python, Java projects
- Project ideas, proposal & documentation
- System design & database design
🌐 Web Design & Development
Websites and database-driven applications for individuals and businesses.
- Website design & development
- WordPress & Blogger
- PHP & MySQL web applications
- Website SEO & maintenance
📢 Digital Marketing
Grow your brand online in the Sri Lankan market.
- Facebook page & Facebook Ads
- Instagram, Reels, TikTok & YouTube
- SEO & content creation
- LinkedIn branding & campaign planning
💻 Computer & IT Skills
Essential computer skills from beginner to advanced.
- Computer fundamentals
- MS Word, Excel & PowerPoint
- Excel formulas & macros
- Oracle / MySQL / MS SQL, AWS, Linux
🗣️ English · සිංහල · தமிழ் – Classes in Your Language
English
Online ICT classes in Sri Lanka, A/L ICT online class, O/L ICT tuition, computer classes, Python classes, web design course, BIT project guidance, digital marketing course Sri Lanka, home visit ICT teacher, Cambridge & Edexcel ICT / Computer Science.
සිංහල
ශ්රී ලංකාවේ ඔන්ලයින් ICT පන්ති, උසස් පෙළ ICT ඔන්ලයින් පන්ති, සාමාන්ය පෙළ ICT පන්ති, පරිගණක පන්ති, පයිතන් (Python) ප්රෝග්රැමින් පන්ති, වෙබ් අඩවි නිර්මාණය, විශ්වවිද්යාල අවසන් වසර ව්යාපෘති මාර්ගෝපදේශනය, ඩිජිටල් මාකටින් පාඨමාලාව, නිවසට පැමිණ උගන්වන ICT ගුරුවරයා.
தமிழ்
இலங்கையில் ஆன்லைன் ICT வகுப்புகள், உயர்தர ICT ஆன்லைன் வகுப்பு, சாதாரண தர ICT வகுப்பு, கணினி வகுப்புகள், பைதான் (Python) நிரலாக்க வகுப்பு, இணையதள வடிவமைப்பு, பல்கலைக்கழக இறுதியாண்டு திட்ட வழிகாட்டல், டிஜிட்டல் மார்க்கெட்டிங் பயிற்சி, வீட்டிற்கு வந்து கற்பிக்கும் ICT ஆசிரியர்.
📚 Learn With Your Curriculum
Sri Lankan local syllabus, Pearson Edexcel and Cambridge programmes – ICT and Computer Science.
🇱🇰 Sri Lankan Local Curriculum
- Grade 1 – Grade 11 ICT
- G.C.E. O/L ICT · සා/පෙළ ICT · சா/த ICT
- G.C.E. A/L ICT · උ/පෙළ ICT · உ/த ICT
- GIT classes
- Term test preparation, model papers & notes
- English / Sinhala / Tamil medium
📘 Pearson Edexcel
- iPrimary Computing
- iLowerSecondary Computing
- International GCSE ICT
- International GCSE Computer Science
- International A Level IT
- International A Level Computer Science
📗 Cambridge
- Cambridge Primary & Lower Secondary Computing
- Cambridge IGCSE ICT
- Cambridge IGCSE Computer Science
- Cambridge O Level Computer Science
- AS & A Level IT
- AS & A Level Computer Science
💻 Programming & Software Development Classes
🎓 BIT, BSc & University Final-Year IT Project Guidance
🧑💻 Project Development
- BIT / BSc / IT / ICT projects
- PHP & MySQL projects
- Python & Java projects
- Web application & database projects
📄 Documentation & Practical
- Project ideas & proposals
- System architecture & database design
- Assignment guidance
- Technical documentation & viva preparation
🧠 AI & Smart Applications
- AI application concepts
- Machine-learning modules
- Automation applications
- Step-by-step coding support
📊 Database, Cloud & IT Professional Training
📱 Digital Marketing & Social Media Training (ඩිජිටල් මාකටින් · டிஜிட்டல் மார்க்கெட்டிங்)
🖥️ Microsoft Office & Digital Skills (පරිගණක පන්ති · கணினி வகுப்புகள்)
🧭 How to Join – 4 Simple Steps
- Message us on WhatsApp – tell us your grade / course, medium (English, Sinhala or Tamil) and your goal.
- Choose your format – online class (island-wide), home-visit class, individual or small group.
- Get your plan – schedule, syllabus coverage, notes, past papers or project roadmap.
- Start learning – live practical sessions with support between classes.
⭐ Why Join Our ICT Classes?
Study from anywhere in Sri Lanka or at home.
One-to-one or small group classes.
Learn in the medium you are comfortable with.
O/L, A/L, Cambridge, Edexcel, BIT, BSc.
Exam-focused practice and revision.
Build real programs, websites and projects.
❓ Frequently Asked Questions – ICT Classes in Sri Lanka
Do you conduct online ICT classes for O/L and A/L students in Sri Lanka?
Yes. We conduct online ICT classes for G.C.E. O/L and A/L students island-wide, and also offer home-visit individual classes. Classes cover the syllabus, past papers, model papers and revision.
Which languages are the classes taught in? (සිංහල / தமிழ் / English)
Classes are available in English, Sinhala and Tamil medium. / පන්ති ඉංග්රීසි, සිංහල සහ දෙමළ මාධ්යයෙන් පවතී. / வகுப்புகள் ஆங்கிலம், சிங்களம் மற்றும் தமிழ் மொழிகளில் நடைபெறும்.
Do you teach Cambridge and Pearson Edexcel ICT and Computer Science?
Yes. We support Cambridge Primary to A Level and Pearson Edexcel iPrimary to International A Level, including IGCSE ICT, IGCSE Computer Science and O Level Computer Science.
Can you help with BIT, BSc or IT final-year projects?
Yes. We give technical guidance on project ideas, system design, database design, PHP & MySQL, Python and Java development, and documentation for BIT, BSc, IT and ICT students.
Can I learn Python, PHP, web design or digital marketing as a complete beginner?
Yes. Courses start from absolute beginner level and move step by step to practical projects. No previous experience is needed.
What are the class fees and schedules?
Fees and timetables depend on the subject, grade and whether you choose individual or group classes. Message us on WhatsApp (+94 72 962 2034) for current details.
How can I contact ITClassSL?
WhatsApp or call +94 72 962 2034, email itclasssl@gmail.com, or message us on Facebook and the other platforms listed below.
📞 Ready to Start Learning?
Book your online ICT class or ask about programming courses, university project guidance and digital marketing training.
📱 Call / WhatsApp: +94 72 962 2034
📧 Email: itclasssl@gmail.com
💻 Skype: ITClassSL
💬 Contact Us on WhatsApp🌐 Our Online Learning Platforms
Tutorials, notes, project guides and learning resources.
ICT & programming videos 💬 WhatsApp Community
Join our learning community ✍️ ICT Blog
Computer classes and tutorials 📰 WordPress
Notes and learning resources 📘 Facebook
Follow our official page 🌐 Wix Website
Our training services 💻 eTeacher Website
Online learning platform 📝 Medium
Technology articles ❓ Quora
Project guidance and Q&A 🎓 Strikingly Portfolio
University project resources 🗣️ ElaKiri Forum
Project discussion 🎵 TikTok
Short learning videos 🛒 Payhip
Digital resources 🌐 Weebly
Project and IT resources