WEEK 4: GUIDELINES
Inheritance & Polymorphism
Week: 4 of 10 | Topics: Inheritance, Polymorphism | Assignment 2: Continue (Defense Week 5)
📚 LEARNING OBJECTIVES
Understand inheritance and create parent-child class hierarchies
Use extends keyword to inherit from parent class
Use super keyword in child constructors
Override parent methods in child classes with @Override annotation
Understand and implement polymorphism
Use ArrayList<ParentType> to store different child objects
Use instanceof operator and downcasting
Demonstrate inheritance and polymorphism in console application
🌳 WHAT IS INHERITANCE?
Inheritance allows you to create new classes based on existing classes. The child class (subclass) inherits fields
and methods from the parent class (superclass).
Why use inheritance?
Code Reusability - Don't repeat the same code
Logical Organization - Group related classes
Polymorphism - Treat different objects the same way
Easy Maintenance - Change parent, all children inherit changes
Real World Example:
Think about vehicles: All vehicles have wheels, engine, speed. But Car has 4 wheels, Motorcycle has 2 wheels.
Both are vehicles, but different!
Vehicle (Parent)
- wheels
- engine
- speed
|
---------------
| |
Car Motorcycle
- doors - helmet
- trunk - kickstand
🔑 KEY CONCEPTS
1. extends Keyword
Use extends to inherit from parent class
public class Chef extends Staff {
// Chef inherits all fields and methods from Staff
}
2. super Keyword
Use super() to call parent constructor
public Chef(int id, String name, double salary, int experience, String
specialization) {
super(id, name, salary, experience); // Call parent constructor
[Link] = specialization; // Initialize child field
}
3. protected Modifier
protected fields are accessible in child classes
public class Staff {
protected int staffId; // Child classes can access directly
protected String name; // Child classes can access directly
private double salary; // Child classes CANNOT access (use getter)
}
4. Method Overriding
Child class can replace parent method with different behavior
// In Parent (Staff)
public void work() {
[Link](name + " is working.");
}
// In Child (Chef)
@Override
public void work() {
[Link]("Chef " + name + " is cooking " + specialization + "
dishes.");
}
🎭 WHAT IS POLYMORPHISM?
Polymorphism means "many forms". One method name can behave differently depending on the object type.
// All are Staff type, but behave differently!
Staff s1 = new Staff(...);
Staff s2 = new Chef(...); // Polymorphism: Chef treated as Staff
Staff s3 = new Waiter(...); // Polymorphism: Waiter treated as Staff
[Link](); // Output: "Aibek is working."
[Link](); // Output: "Chef Murat is cooking Kazakh Cuisine dishes."
[Link](); // Output: "Waiter Dana is serving tables."
// Same method name, different behavior!
instanceof and Downcasting
Use instanceof to check object type, then cast to access child methods
Staff staff = new Chef(...);
// Check type
if (staff instanceof Chef) {
Chef chef = (Chef) staff; // Downcast to Chef
[Link]("Beshbarmak"); // Now can call Chef-specific method
}
💡 INHERITANCE IDEAS FOR YOUR PROJECT
Restaurant:
Parent: Staff → Children: Chef, Waiter, Manager
Parent: MenuItem → Children: MainCourse, Dessert, Beverage
Parent: Customer → Children: RegularCustomer, VIPCustomer
Hospital:
Parent: Person → Children: Patient, Doctor, Nurse
Parent: MedicalStaff → Children: Doctor, Nurse, Surgeon
Parent: Appointment → Children: EmergencyAppointment, RegularAppointment
Vet Clinic:
Parent: Animal → Children: Dog, Cat, Bird
Parent: Pet → Children: DomesticPet, ExoticPet
Parent: Treatment → Children: Surgery, Vaccination, Checkup
Grocery Store:
Parent: Product → Children: FreshProduct, PackagedProduct, FrozenProduct
Parent: Employee → Children: Cashier, StockClerk, Manager
Parent: Discount → Children: PercentageDiscount, FixedAmountDiscount
Clothing Store:
Parent: ClothingItem → Children: Shirt, Pants, Jacket
Parent: Customer → Children: RegularCustomer, VIPCustomer, WholesaleCustomer
Parent: Size → Children: AdultSize, KidsSize
Gym:
Parent: Member → Children: StudentMember, PremiumMember, SeniorMember
Parent: Workout → Children: CardioWorkout, StrengthWorkout, YogaWorkout
Parent: Trainer → Children: PersonalTrainer, GroupTrainer
📋 TECHNICAL REQUIREMENTS
1. Inheritance Structure
✓ Create 1 parent class and minimum 2 child classes
✓ Use extends keyword correctly
✓ Parent class must have minimum 4 protected fields
✓ Each child class adds 1-2 additional fields
✓ Parent must have minimum 3 methods (including work/action method)
2. Constructors with super
✓ Parent class: parameterized constructor
✓ Each child class: parameterized constructor using super()
✓ super() must be FIRST line in child constructor
✓ Child constructor initializes both parent and child fields
3. Method Overriding
✓ Override minimum 2 methods from parent in EACH child
✓ Use @Override annotation
✓ Overridden methods must have different behavior (not just copy parent)
✓ Each child must have 2+ unique methods (not in parent)
4. Polymorphism
✓ Create ArrayList<ParentType> that stores both parent and child objects
✓ Demonstrate polymorphic behavior (call overridden methods through parent reference)
✓ Use instanceof operator to check object type
✓ Perform downcasting when needed to access child-specific methods
🎮 CONSOLE MENU REQUIREMENTS
Your menu must demonstrate inheritance and polymorphism:
Required Menu Options:
1. Add Parent Object
Ask user for parent class fields only, create parent object
2. Add Child Object (Type 1)
Ask for parent fields + child-specific fields
3. Add Child Object (Type 2)
Same for second child type
4. View All Objects (Polymorphic)
Loop through ArrayList<ParentType>, call overridden methods
5. Demonstrate Polymorphism
Show all objects calling same method with different behavior
6. View by Type
Use instanceof to filter and show only specific child type
Example Menu (Restaurant):
========================================
RESTAURANT MANAGEMENT SYSTEM
========================================
1. Add Staff Member (General)
2. Add Chef
3. Add Waiter
4. View All Staff (Polymorphic)
5. Make All Staff Work (Polymorphism Demo)
6. View Chefs Only
7. View Waiters Only
0. Exit
========================================
Enter your choice: _
🔨 IMPLEMENTATION: RESTAURANT EXAMPLE
Step 1: Parent Class (Staff)
public class Staff {
// Protected fields - accessible in child classes
protected int staffId;
protected String name;
protected double salary;
protected int experienceYears;
// Constructor
public Staff(int staffId, String name, double salary, int experienceYears) {
[Link] = staffId;
[Link] = name;
[Link] = salary;
[Link] = experienceYears;
}
// Getters
public int getStaffId() { return staffId; }
public String getName() { return name; }
public double getSalary() { return salary; }
public int getExperienceYears() { return experienceYears; }
// Setters
public void setStaffId(int staffId) { [Link] = staffId; }
public void setName(String name) { [Link] = name; }
public void setSalary(double salary) {
if (salary >= 0) [Link] = salary;
}
public void setExperienceYears(int experienceYears) {
if (experienceYears >= 0) [Link] = experienceYears;
}
// Method to be overridden
public void work() {
[Link](name + " is working.");
}
// Another method to be overridden
public String getRole() {
return "Staff Member";
}
// Method that won't be overridden
public boolean isExperienced() {
return experienceYears >= 5;
}
@Override
public String toString() {
return "[" + getRole() + "] " + name + " (ID: " + staffId +
", Salary: " + salary + " KZT, Experience: " + experienceYears + " years)";
}
}
Step 2: Child Class 1 (Chef)
public class Chef extends Staff {
// Additional field specific to Chef
private String specialization;
// Constructor - uses super() to call parent constructor
public Chef(int staffId, String name, double salary, int experienceYears,
String specialization) {
super(staffId, name, salary, experienceYears); // MUST BE FIRST!
[Link] = specialization;
}
// Getter and Setter for new field
public String getSpecialization() {
return specialization;
}
public void setSpecialization(String specialization) {
[Link] = specialization;
}
// Override method 1
@Override
public void work() {
[Link]("Chef " + name + " is cooking " + specialization + " dishes.");
}
// Override method 2
@Override
public String getRole() {
return "Chef";
}
// New method specific to Chef
public void cookDish(String dishName) {
[Link]("Chef " + name + " is preparing: " + dishName);
}
// Another new method
public boolean isMasterChef() {
return experienceYears >= 10;
}
@Override
public String toString() {
return [Link]() + " | Specialization: " + specialization;
}
}
Step 3: Child Class 2 (Waiter)
public class Waiter extends Staff {
// Additional field specific to Waiter
private int tablesServed;
// Constructor - uses super()
public Waiter(int staffId, String name, double salary, int experienceYears,
int tablesServed) {
super(staffId, name, salary, experienceYears);
[Link] = tablesServed;
}
// Getter and Setter
public int getTablesServed() {
return tablesServed;
}
public void setTablesServed(int tablesServed) {
if (tablesServed >= 0) [Link] = tablesServed;
}
// Override method 1
@Override
public void work() {
[Link]("Waiter " + name + " is serving tables.");
}
// Override method 2
@Override
public String getRole() {
return "Waiter";
}
// New method specific to Waiter
public void serveTable(int tableNumber) {
[Link]("Waiter " + name + " is serving table #" + tableNumber);
tablesServed++;
}
// Another new method
public boolean isTopWaiter() {
return tablesServed > 100 && experienceYears >= 3;
}
@Override
public String toString() {
return [Link]() + " | Tables Served: " + tablesServed;
}
}
Step 4: Main Class with Polymorphism
Key changes to your Week 3 Main class:
// CHANGE 1: Use parent type for ArrayList
private static ArrayList<Staff> allStaff = new ArrayList<>(); // Was: ArrayList<Chef>,
ArrayList<Waiter>
// CHANGE 2: Add polymorphic objects
[Link](new Staff(1001, "Aibek", 400000, 5));
[Link](new Chef(2001, "Murat", 600000, 12, "Kazakh Cuisine"));
[Link](new Waiter(3001, "Dana", 300000, 4, 95));
// CHANGE 3: Loop shows polymorphism
for (Staff s : allStaff) {
[Link](); // Different behavior for each type!
}
New Menu Methods:
addChef() Method:
private static void addChef() {
[Link]("\n--- ADD CHEF ---");
[Link]("Enter staff ID: ");
int id = [Link]();
[Link]();
[Link]("Enter name: ");
String name = [Link]();
[Link]("Enter salary: ");
double salary = [Link]();
[Link]();
[Link]("Enter experience years: ");
int experience = [Link]();
[Link]();
[Link]("Enter specialization: ");
String spec = [Link]();
// Create Chef but store as Staff (polymorphism!)
Staff staff = new Chef(id, name, salary, experience, spec);
[Link](staff);
[Link]("\n✅ Chef added successfully!");
}
viewAllStaff() - Polymorphic Method:
private static void viewAllStaff() {
[Link]("\n========================================");
[Link](" ALL STAFF (POLYMORPHIC LIST)");
[Link]("========================================");
if ([Link]()) {
[Link]("No staff members found.");
return;
}
[Link]("Total staff: " + [Link]());
[Link]();
for (int i = 0; i < [Link](); i++) {
Staff s = [Link](i);
[Link]((i + 1) + ". " + s); // Calls overridden toString()
// Use instanceof to check type and show child-specific info
if (s instanceof Chef) {
Chef chef = (Chef) s; // Downcast
👨🍳
if ([Link]()) {
[Link](" Master Chef!");
}
} else if (s instanceof Waiter) {
Waiter waiter = (Waiter) s; // Downcast
⭐
if ([Link]()) {
[Link](" Top Waiter!");
}
}
[Link]();
}
}
demonstratePolymorphism() Method:
private static void demonstratePolymorphism() {
[Link]("\n========================================");
[Link](" POLYMORPHISM DEMONSTRATION");
[Link]("========================================");
[Link]("Calling work() on all staff members:");
[Link]();
for (Staff s : allStaff) {
[Link](); // Polymorphism: Same method, different behavior!
}
✨ Notice: Same method name (work), different output!");
[Link]();
[Link]("
[Link](" This is POLYMORPHISM in action!");
}
viewChefs() - Filter by Type:
private static void viewChefs() {
[Link]("\n========================================");
[Link](" CHEFS ONLY");
[Link]("========================================");
int chefCount = 0;
for (Staff s : allStaff) {
if (s instanceof Chef) { // Filter by type
Chef chef = (Chef) s; // Downcast to access Chef methods
chefCount++;
[Link](chefCount + ". " + [Link]());
[Link](" Specialization: " + [Link]());
[Link](" Experience: " + [Link]() + " years");
👨🍳 Master Chef");
if ([Link]()) {
[Link]("
}
[Link]();
}
}
if (chefCount == 0) {
[Link]("No chefs found.");
}
}
📺 EXPECTED CONSOLE OUTPUT
========================================
RESTAURANT MANAGEMENT SYSTEM
========================================
1. Add Staff Member (General)
2. Add Chef
3. Add Waiter
4. View All Staff (Polymorphic)
5. Make All Staff Work
6. View Chefs Only
7. View Waiters Only
0. Exit
========================================
Enter your choice: 4
========================================
ALL STAFF (POLYMORPHIC LIST)
========================================
Total staff: 4
1. [Staff Member] Aibek (ID: 1001, Salary: 400000.0 KZT, Experience: 5 years)
👨🍳
2. [Chef] Murat (ID: 2001, Salary: 600000.0 KZT, Experience: 12 years) | Specialization: Kazakh Cuisine
Master Chef!
3. [Waiter] Dana (ID: 3001, Salary: 300000.0 KZT, Experience: 4 years) | Tables Served: 95
4. [Chef] Aidar (ID: 2002, Salary: 550000.0 KZT, Experience: 7 years) | Specialization: European Cuisine
Press Enter to continue...
========================================
RESTAURANT MANAGEMENT SYSTEM
========================================
Enter your choice: 5
========================================
POLYMORPHISM DEMONSTRATION
========================================
Calling work() on all staff members:
Aibek is working.
Chef Murat is cooking Kazakh Cuisine dishes.
Waiter Dana is serving tables.
Chef Aidar is cooking European Cuisine dishes.
✨ Notice: Same method name (work), different output!
This is POLYMORPHISM in action!
Press Enter to continue...
========================================
RESTAURANT MANAGEMENT SYSTEM
========================================
Enter your choice: 6
========================================
CHEFS ONLY
========================================
1. Murat
Specialization: Kazakh Cuisine
👨🍳
Experience: 12 years
Master Chef
2. Aidar
Specialization: European Cuisine
Experience: 7 years
Press Enter to continue...
✅ IMPLEMENTATION CHECKLIST
Code Structure:
☐ 1 parent class file (e.g., [Link])
☐ 2+ child class files (e.g., [Link], [Link])
☐ All child classes use extends
☐ All child classes use super() in constructor
☐ Minimum 2 @Override methods per child
Polymorphism in Action:
☐ One ArrayList<ParentType> stores all objects
☐ Can add both parent and child objects to same list
☐ Loop through list and call overridden methods
☐ Output shows different behavior for different types
☐ Use instanceof to check types
☐ Use casting to access child-specific methods
Console Menu:
☐ Menu has options to add each type (parent + children)
☐ Menu has "View All" showing polymorphic list
☐ Menu has "Demonstrate Polymorphism" option
☐ Menu shows object types clearly [Staff]/[Chef]/[Waiter]
☐ User can see inheritance in action
☐ instanceof used to show child-specific badges/info
⚠️ COMMON MISTAKES TO AVOID
1. Separate ArrayLists: Don't create ArrayList<Chef> and ArrayList<Waiter> separately. Use ONE
ArrayList<Staff>!
2. Not using polymorphism: Wrong: Chef chef = new Chef(...)
Correct: Staff staff = new Chef(...) // Polymorphism!
3. Empty @Override: Don't just copy parent method. Make it different!
Wrong: Same output as parent
Correct: Different behavior specific to child
4. Forgetting super(): Child constructor MUST call super() as FIRST line!
5. Wrong instanceof check: Check parent type first, then child: if (s instanceof Chef) not if (Chef instanceof
s)
6. Not demonstrating polymorphism: Console MUST show that same method call produces different
results!
💡 TIPS FOR SUCCESS
Start with parent class - make sure it works first
Create one child class, test it, then create second child
Test polymorphism early - create ArrayList<Parent> and add children
Make overridden methods obviously different from parent
Use [Link] in overridden methods to show difference
Test instanceof and casting before adding to menu
Add comments explaining where you use polymorphism
Run your "Demonstrate Polymorphism" menu option to verify it works
📋 WEEK 4 SUMMARY
Concept Key Points
Inheritance • extends keyword
• Parent and child classes
• protected fields
• Code reusability
super Keyword • Calls parent constructor
• Must be FIRST line
• super(parent_fields)
@Override • Replaces parent method
• Different behavior
• Use annotation
Polymorphism • Parent reference, child object
• Same method, different behavior
• ArrayList<Parent> stores children
instanceof • Check object type
• Use before casting
• Filter by type
Downcasting • Cast parent to child
• Access child methods
• (ChildType) parent
Master Inheritance & Polymorphism! 🚀