0% found this document useful (0 votes)
11 views7 pages

Java OOP Concepts and Applications Guide

Important Topics1

Uploaded by

Anil Kumar B
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)
11 views7 pages

Java OOP Concepts and Applications Guide

Important Topics1

Uploaded by

Anil Kumar B
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

Module Bank Questions

Object Oriented Programming using Java


Module-1 T1

1Q a) Design a class Student with:Fields: name, rollNo, marks[]Method:


calculateAverage(), displayDetails() Create an array of Student objects and analyze:
The topper The student who needs improvement (lowest average) Display only those
who scored above class average.
b) Modify the Student class-based application to validate input using exception
handling: Ensure marks are not negative or above [Link] invalid marks are entered,
throw and catch a custom exception InvalidMarkException
c) Using the 2D marks array, perform subject-wise analysis:Compute and display the
average mark per [Link] the subject in which the class performed best
and worst overall.

2Q a) A small library is developing a digital catalog system to store book records.


Each book record includes its title and author. The system must support both default
book entries (used for placeholders or unknown entries) and detailed book entries
(entered by staff with complete information). The system should also allow displaying
book details for verification purposes.
a) Analyze the Requirements
Why would a library system need both a default and a parameterized constructor?
In what situations might a placeholder book entry be useful?
b) Apply Object-Oriented Concepts
Design and implement a Book class with the following features:
Two instance variables: title and author
A default constructor that sets sample data like "Unknown Title" and "Unknown
Author"
A parameterized constructor that takes custom values for title and author
A method displayDetails() to display the book’s information
c) Create a Working Demo
In the main() method, create two Book objects:
One using the default constructor
One using the parameterized constructor
Display the details of both books using the displayDetails() method.

3Q.) Design a application that demonstrates the use of the super keyword in a real-
world employee management scenario.
a) An organization wants to digitize its HR system to manage employee data.
Employees belong to different departments, and managers need to be identified
with additional details. The HR system should display employee information
efficiently using inheritance and method overriding, while also distinguishing
managers from general employees.
b) Define a superclass Employee with attributes like employeeId, name, and a
method displayInfo().Create a subclass Manager that extends Employee and adds
a new attribute like department.
c) In the Manager class, override the displayInfo() method and use
[Link]() to reuse base class [Link] the main() method, create a
Manager object and display all information using the overridden method.

4Q. a) Design and implement a application to simulate a simple food ordering system
using a switch statement. Requirements: Prompt the user to enter a dish code as input.
Based on the entered code, display: The name of the dish Its price The final bill
amount Include an option to exit the program gracefully
b) Extend the simple food ordering system to support multiple orders and quantity-
based billing using a switch statement and loop.
c) Prompt the user repeatedly using a loop to: Select a dish by entering a dish code.
Enter the quantity of the selected dish Calculate the subtotal (price × quantity)
Maintain a running total bill for all items ordered Allow ordering multiple dishes
in a single session Exit the loop when the user selects option 4 (Exit)
After exiting, display: A summary of the total number of items. The final total bill
amount.
5Q. a) Clearly distinguish between method overloading and method overriding in
Java. Compare their purpose, rules, and use cases
b) Design a Java class named Area Calculator that demonstrates method overloading
by defining multiple calculateArea() methods.
Implement the calculateArea(double radius) – to compute the area of a circle
calculateArea(int length, int breadth) – to compute the area of a rectangle
calculateArea(double base, double height) – to compute the area of a triangle
Each method should print the shape name, input values, and calculated area.
c) Extend the Area Calculator class to include the following functionality: Add a
menu-driven interface in the main() method that allows the user to: Select a shape
(circle, rectangle, triangle)Enter relevant dimensions . Call the appropriate overloaded
method to calculate and display the area

6Q. a) Describe how Java classes can be used to represent patients, doctors, and
appointments in a healthcare scheduling system and describe how encapsulation helps
in securing sensitive patient information. Also classify how different appointment
states such as available, booked, and cancelled can be handled in the system.
b) Implement a Java application using classes and interfaces to manage patient and
doctor details for scheduling and canceling appointments. Apply exception handling
to prevent double-booking and invalid cancellations, ensuring that only valid
appointments are confirmed. Use encapsulation to restrict direct access to sensitive
appointment data and maintain data integrity within the application.
c) Develop a complete healthcare appointment scheduling system in Java that
integrates patient management, doctor availability tracking, and appointment conflict
detection. Use a fixed-size array to store appointments,use inheritance by creating a
base Person class extended by Patient and Doctor, and use an interface for sending
booking notifications. Include exception handling for time conflicts and missing
records, ensuring proper reporting of appointment history.
7Q. a) Distinguish between private, public, and protected access modifiers in Java.
Support your explanation with examples demonstrating how each modifier controls
access to class members.

b) Implement encapsulation in a Student class by restricting direct access to the GPA


field. Requirements: Declare the gpa field as private Provide public getter and setter
methods: getGPA() – to retrieve the GPA, set GPA(double gpa) – to update the
GPAIn the main() method: Create a Student object Attempt to access gpa directly
(show that it's restricted)Use the setter to assign a value and the getter to display it

c) Enhance the Student class by adding input validation inside the setGPA() method.
Requirements: Modify setGPA(double gpa) to allow only valid GPA values between
0.0 and 10.0If an invalid GPA is provided: Display an appropriate error message (e.g.,
"Invalid GPA. Please enter a value between 0.0 and 10.0.")Do not update the GPA

8Q. a) Compare interfaces and classes . Discuss how they differ in terms of definition,
implementation, and behavior using suitable examples.

b) implement a health care service system using interfaces and classes.

Task:Create an interface named HealthService with a method:


void servePatient();Implement this interface in the following classes:Doctor, Nurse,
LabTechnician. In each class, provide a specific implementation of servePatient() that
reflects their role (e.g., "Doctor diagnoses the patient", "Nurse provides medication",
etc.). In the main() method, create objects of each class and call the servePatient()
method to demonstrate polymorphic behavior.

. c) Extend the above implementation to use an array of HealthService references.

Requirements:Store Doctor, Nurse, and LabTechnician objects in a HealthService[]


[Link] a loop to iterate over the array and call servePatient() on each
[Link] how this design demonstrates polymorphism and improves scalability
when adding more roles (e.g., Physiotherapist, Pharmacist).
9Q. a) You are working as a Java developer on a banking application. During
transactions like withdrawals and balance inquiries, various exceptions might occur—
such as invalid input, arithmetic errors, or accessing null references. To ensure a
smooth user experience and stable application behavior, it is important to understand
and implement proper exception handling using Java’s exception class hierarchy.

b) You are developing a university registration system. Students can register for
courses online. However, if a student tries to enroll in a course that has already
reached the maximum capacity, the system should handle this gracefully. You need to
decide whether to use Java's built-in exceptions or define a custom exception to better
represent this business rule.

c) Implement a custom exception to handle full course registration scenarios.

i. Create a custom exception class named SeatFullException that extends Exception.


Create a class Course with the following attributes:courseNamemaxSeats,
currentSeats.
ii. Add a method registerStudent() that:Checks if seats are availableIf yes,
increments currentSeats and confirms registration .If not, throws SeatFullException
with a meaningful message (e.g., "Cannot register. Course is full.").
iii. In the main() method:Create a course with limited seatsAttempt to register
more students than the available seats .Handle the exception using a try-catch
block
.
10Q. a) Discuss how an employee ID can be searched within a list of stored IDs and
describe the way it can be updated when required. Also classify how the system
should handle cases where the given ID exists and when it is not found in the records.

b) Implement an application that manages employee contact information by creating a


Contact class and an interface to handle details such as phone number, email
addresses, and social media links. Use the application to store sample details of an
employee and retrieve them for display. Ensure that the system validates the entered
contact information and prevents invalid data from being shown to the user
c) Design an employee management system that introduces an abstract Employee
class containing shared attributes like employee ID, name, and salary along with
common methods

11Q. a) Which class will use for reading the input from the user in java and for
reading the different types of data what are the methods we use

b) Create a class Rectangle. The class has attributes length and width. It should have
methods that calculate the perimeter and area of the rectangle. It should have read
Attributes method to read length and width from user . To create a Rectangle
class with attributes length and width. The class should have methods tocalculate
the perimeter and area of the rectangle and a method to read these attributes from
the user.

12Q.) A company is developing a Smart Vehicle [Link] GPS: Contains


methods for location tracking and [Link] MusicPlayer: Contains
methods for playing, pausing, and stopping [Link] SmartCar: Needs to support
both GPS and music player functionalities.

a) Explain why Java does not support multiple inheritance with classes, but allows it
with interfaces.
b) Show how the SmartCar class can implement both GPS and MusicPlayer
interfaces to achieve multiple inheritance behavior.
c) If both interfaces have a default method named start(), explain how Java resolves
this conflict and how you would explicitly choose which one to use.
13Q.) A company is building a Library Management System in [Link] want to
organize their code into packages and use inheritance to avoid duplication. The
system must also handle exceptional situations gracefully.

Requirements: Package [Link] Class Book: Stores details like title, author, and
price. Class EBook (inherits from Book): Adds file size and format. Package
[Link] Class Member: Stores member details like name and ID. Class
PremiumMember (inherits from Member): Adds extra borrowing limits.

Package [Link] Custom Exception BookNotAvailableException: Thrown


when a requested book is not available. Main application (in [Link] package)
Allows a member to borrow a book. If the book is unavailable, the system throws and
handles BookNotAvailableException

a) Draw a package diagram showing all the packages and classes with their
relationships.
b) Explain how inheritance is used in this system to reduce code duplication.
c) Write Java code to define the BookNotAvailableException class and demonstrate
how it would be thrown and caught in the main application.

Common questions

Powered by AI

The key difference between method overloading and method overriding in Java lies in their definitions and use cases. Method overloading occurs within a single class when multiple methods have the same name but different parameter lists, allowing different implementations based on input types, enhancing readability and reusability. In contrast, method overriding involves providing a specific implementation of a method already defined in a superclass, promoting dynamic polymorphism. In an Area Calculator class, method overloading can demonstrate these principles by defining multiple `calculateArea()` methods with varying parameters for different shapes: circle, rectangle, and triangle. Meanwhile, method overriding would apply in a subclass context where these methods might be further refined .

Exception handling in a student management system for validating marks ensures the application remains robust by preventing the processing of invalid data. Introducing a custom exception such as 'InvalidMarkException' allows the system to specifically handle scenarios when marks fall outside the permissible range (0 to 100). This approach not only maintains data integrity by ensuring only valid marks are recorded but also improves the user experience by providing specific error messages, thereby guiding users to correct input mistakes .

In an employee management scenario, the 'super' keyword is employed to call the base class's method logic within an overridden method in a subclass. For instance, in the Manager class, which inherits from Employee, 'super.displayInfo()' allows the Manager's displayInfo() method to utilize the existing logic in Employee's displayInfo() method before adding additional functionality, such as displaying department information. This not only promotes code reuse but also ensures that managers' unique complexities are seamlessly integrated with the shared employee data presentation logic .

Interfaces in Java provide a way to implement multiple inheritance by allowing a class to adopt the behavior of multiple interfaces, whereas classes define a structure with state through fields and behaviors through methods. Using interfaces such as `HealthService`, a class like `Doctor` can implement it to define role-specific methods such as `servePatient()`. This structure both demonstrates polymorphism and supports scalability as new roles can be introduced with minimal impact on existing code. In a healthcare service system, interfaces allow for flexible role implementation, supporting changes and extensions that add complexity without disrupting existing operations .

Java supports multiple inheritance through interfaces because it avoids the diamond problem seen in class-based multiple inheritance, where a subclass inherits conflicting definitions from multiple superclasses. In contrast, interfaces only define method signatures without implementation, allowing classes like SmartCar to implement multiple behaviors (e.g., GPS, MusicPlayer) without ambiguity. This distinction allows developers to build complex systems where separate functionalities can be modularly attached to a single class, thereby enhancing flexibility and scalability without the complications of conflicting inherited states or behaviors .

Defining a custom exception like `SeatFullException` in a university registration system improves error handling by providing more meaningful and specific messages when a course is full. Instead of relying on generic exception messaging, this custom approach tailors the error response to the specific registration context, informing the user precisely why the registration failed. This specificity not only enhances the user experience by providing clear guidance but also facilitates debugging and system maintenance by encapsulating business logic within exception handling constructs that are contextually relevant .

An abstract Employee class provides a base structure for shared attributes and methods (like employee ID, name, and salary), reducing code duplication and promoting consistency across subclasses. This setup allows specific subclasses (e.g., Manager) to extend and implement additional behaviors or attributes unique to their roles. Access modifiers such as private, public, and protected, within this context, enforce data encapsulation and security by controlling the visibility and access level of these fields and methods. For instance, setting variables private ensures they are only accessed through getters/setters, maintaining control over sensitive data changes and preventing unauthorized access .

Using both default and parameterized constructors in a library's digital catalog system fulfills different needs. The default constructor can create placeholder book entries with generic titles like 'Unknown Title' and 'Unknown Author', useful for temporary or incomplete records. In contrast, the parameterized constructor allows staff to input specific details for a book, ensuring the record is precise and complete. This dual constructor setup provides flexibility in data handling, enabling efficient management of both known and unknown book information .

Encapsulation enhances data security in a healthcare scheduling system by restricting direct access to sensitive patient information and appointment data. This approach ensures that such data is only accessed or modified through well-defined methods, reducing the risk of unauthorized access or data corruption. Encapsulation allows developers to implement validation logic within these methods, ensuring that the scheduling and management of appointments adhere to business rules and maintain system integrity. For example, encapsulation can prevent double-booking by validating inputs within setter methods or specific appointment methods .

A Java application can simulate a food ordering system using switch statements by prompting the user to enter a dish code and then using the switch to match the code with corresponding dish information, including name and price. Extending the system to handle multiple orders involves adding loops to repeat this process for additional inputs, maintaining a running total for all orders, and allowing the user to exit gracefully. This extension increases system functionality by supporting quantity-based billing and displaying a final summary of the total bill once ordering is complete .

You might also like