Java Assignment- 3

Object Oriented Programming

Basic Questions

  1. In simple words, explain what Object-Oriented Programming (OOP) is and list four core principles (encapsulation, inheritance, polymorphism, abstraction) with one short benefit of each.
  2. Create a class Student with fields id, name. Create an object in main, set values, and print them in a readable sentence.
  3. Create a class Course with a default constructor that sets title = “Java Basics” and durationWeeks = 6. Create an object and print both values.
  4. Create a class Trainer with a parameterized constructor that sets name and expertise. Create two objects with different data and print their details.
  5. Create a class Batch with two constructors: a default constructor and another that takes code and size. Use this() to chain from the parameterized constructor to the default one. Print values from both.
  6. Create a class CounterDemo with a static variable count and an instance variable label. Increase count in each object’s constructor. Create three objects with different labels and print each label and the final count.
  7. Create a class Laptop with private fields brand and price. Add public getters and setters. In main, set values using setters and print them using getters.
  8. Create a base class User with field name. Create a derived class Admin that extends User and adds role = “ADMIN”. Create an Admin object and print both name and role.
  9. Write a class Calculator that overloads a method add:
    add(int, int) and add(double, double). Call both and print results.
  10. Create a base class Person with a method greet() that prints “Hello”. Create a subclass Employee that overrides greet() to print “Hello from Employee”. Call both versions and observe the output.
  11. Create a class Department with a constructor that takes name. Create a subclass ITDepartment whose constructor uses super(name) to call the parent constructor. Print both department names.
  12. Create a class Plan with a final variable BASE_FEE = 499 and a method that prints it. Try to reassign BASE_FEE (comment the line) and explain in a comment why it fails.
  13. Create a class ImmutableNote with private final fields title and body, a constructor to set them, and only getters. Create an object and print values.
  14. Create an abstract class Shape with an abstract method area(). Create a subclass Circle that implements area() using πr². Create an object and print area.
  15. Create an interface Payable with a method pay(double amount). Create a class Wallet that implements Payable and prints a payment message. Call pay().
  16. Create an interface Reportable with a default method printHeader() that prints “=== Report ===”. Implement it in class SalesReport and call printHeader().
  17. Create two interfaces Auditable and Loggable both with a default method info(). Create a class that implements both and resolve the default method conflict by overriding info().
  18. Show compile-time polymorphism by creating a class Printer with overloaded print(String), print(int), print(double). Call all three in main.
  19. Show runtime polymorphism by creating a base class Notification with send(), and two subclasses EmailNotification and SmsNotification that override send(). Store them in a Notification[] and call send() in a loop.
  20. Create a class FinalExample with a final method rules(). Create a subclass and show (by commented code) that you cannot override a final method.

Intermediate Questions

  1. Create a class StudentProfile with private fields and public getters/setters. Add a method updateEmail(String) that validates non-empty input before setting. Demonstrate encapsulation by preventing direct field access.
  2. Build a small class hierarchy: User → Staff → Trainer (single and multilevel inheritance). Add a describe() method in each that prints a specific message. Create a Trainer object and call describe() to see which version runs.
  3. Create a class LibraryBook with overloaded constructors: (title), (title, author), (title, author, year). Use this(…) to chain them and set defaults. Print a created object’s data.
  4. Create a class Employee with static field companyName and instance fields id, name. Set companyName = “Learn2Earn Labs” and create two employees. Print companyName and each employee’s data.
  5. Create a base class Account with method getInterestRate() returning 5.0. Create subclass SavingsAccount that overrides it to return 6.5. Demonstrate method overriding.
  6. Create a class Coach with a constructor that prints “Coach created”. Create subclass CricketCoach that calls the parent constructor using super() and then prints “CricketCoach ready”. Create an object and show the order of prints.
  7. Create a final class SecurityPolicy. Try to extend it in CustomPolicy (commented code) and explain in a comment why it is not allowed.
  8. Create an abstract class Report with abstract generate() and a concrete printFooter() method. Create SalesReport and AttendanceReport classes that implement generate() differently. Call both methods.
  9. Create an interface Exportable with methods toCSV() and a default metadata(). Implement Exportable in class StudentRecord. Call both methods and print results.
  10. Create two interfaces Storable (method save()) and Retrievable (method load()). Create a class FileRepository that implements both and prints simple messages in each method.
  11. Create a class OrderService with overloaded placeOrder(int id), placeOrder(int id, int qty), and placeOrder(int id, int qty, String note). Demonstrate all calls.
  12. Create a base class Vehicle with describe() and subclasses Car and Bike that override describe(). Write a method printVehicle(Vehicle v) that calls describe(). Pass objects of Car and Bike to show runtime polymorphism.
  13. Create a class Enrollment with private fields studentId and courseId. Add getters/setters with basic checks (e.g., positive IDs). Show how encapsulation protects invalid data.
  14. Create a small example to show that method overloading is decided at compile time: write two printInfo methods for different parameter types and show which one runs based on the variable’s declared type.
  15. Create a class Person with field name in the parent and name again in subclass StudentPerson. Use super.name in the subclass to print the parent’s name and this.name to print the child’s name.
  16. Create a class ConstantHolder with a final static variable MAX_STUDENTS = 100. Print it from main without creating an object. Explain in a comment why this works.
  17. Create an interface Discountable with default method rate() returning 0.05. Create a class FestivalDiscount that overrides rate() to return 0.15. Call both and print the discount rate.
  18. Create an abstract class NotificationService with an abstract method notify(String msg) and a concrete log(String msg). Implement EmailService and SmsService. Demonstrate both abstract and concrete method calls.
  19. Create a small example of hierarchical inheritance: base Employee, subclasses Developer, Tester, Designer. Give each a method work(). Store them in an Employee[] and call work() in a loop.
  20. Create a class PrinterService with an overloaded method print(Object o) and print(String s). Pass a String reference held in a variable of type Object and observe which method is called. Explain in comments how overloading resolution occurs.

Advanced Questions

  1. Design an OOP model for a simple Learning Management System (LMS) using only arrays. Create an abstract class User with a method describe(), subclasses Student and Instructor overriding describe(), and store them in a User[]. Loop over the array and call describe() to show runtime polymorphism.
  2. Create a base class Payment with process() and subclasses CashPayment and CardPayment that override process(). Add an interface Refundable with refund(). Implement Refundable only in CardPayment. Show how polymorphism works when calling through Payment and through Refundable.
  3. Demonstrate multiple inheritance via interfaces: create Downloadable (method download()), Verifiable (method verify() with a default implementation), and a class DigitalCertificate that implements both. Resolve any default method conflicts if you add one intentionally.
  4. Build an example showing constructor chaining across three levels: Person → Employee → Manager. Use this(…) inside Person to chain constructors and super(…) in each subclass. Print the order of constructor calls.
  5. Create an abstract class Document with fields title and owner, an abstract render(), and a concrete printInfo(). Create PdfDocument and WordDocument subclasses. Store them in a Document[] and call render() and printInfo() to show runtime polymorphism.
  6. Write a small demo that shows how a final method in the parent (BasePolicy.enforce()) protects a rule from being changed in the child (ChildPolicy). Explain in comments why this guarantees consistent behavior.
  7. Create two interfaces A and B that both have a default method greet(). Create a class C that implements both and must override greet() to choose behavior. Inside greet(), call one of the interface default methods using A.super.greet() or B.super.greet() and print a combined message.
  8. Create an example of compile-time vs runtime polymorphism on the same class: overload calculate(int, int) and calculate(double, double) (compile-time), and override calculate in a subclass AdvancedCalculator (runtime). Show both behaviors in main.
  9. Create a plugin-like design: define an interface Exporter with export(String data). Implement CsvExporter and JsonExporter. Write a factory method getExporter(String type) in a separate ExportFactory class that returns the correct implementation. In main, choose the exporter based on user input and call export().
  10. Create an interface Command with execute(). Implement two commands StartCommand and StopCommand. Keep a Command[] of length 2 and a parallel String[] of names {“start”,”stop”}. Read a command name from the user, find its index with a simple loop, and run the matching Command from the array. Do not use collections.