Appearance
Answers
1. What is:
Class: A user-defined reference type (blueprint) that groups fields and methods; it holds no data until an object is created.
javaclass Car { int speed; void drive() { System.out.println("Driving"); } }Object: A runtime instance of a class with its own state; variables of the class type store references to objects.
javaCar myCar = new Car(); myCar.speed = 50; myCar.drive();Method: A named block of code tied to a class/object that performs actions, often reading/writing the object’s fields.
javaclass Car { int speed; void accelerate(int delta) { speed += delta; } }Constructor: A special method (no return type) that runs on
newto set initial state.javaclass Car { int speed; Car(int s) { speed = s; } }Method Overloading: Same method name with different parameter lists in the same class; resolved at compile time.
javaclass Car { void drive() {} void drive(int km) {} }Method Overriding: A subclass provides its own implementation of a superclass method with the same signature; enables runtime polymorphism.
javaclass SportsCar extends Car { @Override void drive() { System.out.println("Fast drive"); super.drive(); } }Constructor Overloading: Multiple constructors with different params for flexible object creation.
javaclass Car { int speed; Car() { speed = 0; } Car(int s) { speed = s; } }Encapsulation: Hiding fields (private) and exposing controlled access to protect invariants.
javaclass Car { private int speed; int getSpeed() { return speed; } void setSpeed(int s) { speed = s; } }Inheritance: A subclass reuses and extends parent members using
extends.javaclass SportsCar extends Car { boolean turbo; }Polymorphism: A supertype reference can point to a subtype; overridden methods are chosen at runtime (dynamic dispatch).
javaCar ref = new SportsCar(); ref.drive();
2. Scenario Solutions
k. Vehicle Maintenance Tracker
java
class Vehicle {
private String modelName;
private int manufactureYear;
private String vehicleId;
Vehicle(String modelName, int manufactureYear, String vehicleId) {
this.modelName = modelName;
this.manufactureYear = manufactureYear;
this.vehicleId = vehicleId;
}
String getvehicleId() {
return vehicleId;
}
void setvehicleId(String vehicleId) {
this.vehicleId = vehicleId;
}
String getmodelName() {
return modelName;
}
int getmanufactureYear() {
return manufactureYear;
}
}
class Car extends Vehicle {
double totalDistance;
Car(String modelName, int manufactureYear, String vehicleId) {
super(modelName, manufactureYear, vehicleId);
this.totalDistance = 0;
}
void addDistance(double km) {
totalDistance += km;
}
void showStatus() {
String model = getmodelName();
int year = getmanufactureYear();
String ageCategory;
if (year == 2025) {
ageCategory = "New";
} else {
ageCategory = "Old";
}
System.out.println("Model:" + model + " Age Category:" + ageCategory + " Total Distance:" + totalDistance);
}
void scheduleMaintenance() {
if (totalDistance > 15000) {
System.out.println("Maintenance is needed.");
} else {
System.out.println("No need of Maintenance");
}
}
}
class MaintenanceService {
void performService(Vehicle v) {
System.out.println("General service is performed on vehicle ID: " + v.getvehicleId());
}
}
class CarMaintenanceService extends MaintenanceService {
@Override
void performService(Vehicle v) {
if (v instanceof Car) {
Car c = (Car) v;
System.out.println("General service is performed on car ID: " + c.getvehicleId());
} else {
super.performService(v);
}
}
}
class VehicleMaintenanceTracker {
public static void main(String[] args) {
Car c1 = new Car("Honda", 2024, "24Kh");
c1.addDistance(10000);
c1.scheduleMaintenance();
c1.addDistance(25000);
c1.scheduleMaintenance();
c1.showStatus();
MaintenanceService service1 = new MaintenanceService();
MaintenanceService service2 = new CarMaintenanceService();
service1.performService(c1);
service2.performService(c1);
}
}l. Online Course Enrollment System
java
class Person {
String name;
String email;
private String userId;
Person(String name, String email, String userId) {
this.name = name;
this.email = email;
this.userId = userId;
}
String getUserId() {
return userId;
}
void setUserId(String userId) {
this.userId = userId;
}
}
class Student extends Person {
int completedCourses;
Student(String name, String email, String userId) {
super(name, email, userId);
this.completedCourses = 0;
}
void completeCourse() {
completedCourses++;
}
void displayStudentInfo() {
String Learninglevel;
if (completedCourses < 3) {
Learninglevel = "Beginner";
} else if (completedCourses >= 3 && completedCourses < 5) {
Learninglevel = "Intermediate";
} else {
Learninglevel = "Advanced";
}
System.out.println("Student Name:" + name + " Learning Level:" + Learninglevel + " Total course Done:" + completedCourses);
}
void resetProgress() {
completedCourses = 0;
}
}
class Course {
String getCourseType() {
return "General course";
}
}
class ProgrammingCourse extends Course {
@Override
String getCourseType() {
return "Programming Course";
}
}
class MathCourse extends Course {
@Override
String getCourseType() {
return "Math Course";
}
}
class OnlineCourseEnrollmentSystem {
public static void main(String[] args) {
Student s1 = new Student("Korim", "korim@gmail.com", "1234");
Course c1 = new MathCourse();
Course c2 = new ProgrammingCourse();
s1.completeCourse();
s1.completeCourse();
s1.displayStudentInfo();
System.out.println(c1.getCourseType());
System.out.println(c2.getCourseType());
}
}m. Smart Pet Monitoring System
java
class Pet {
String petName;
String species;
private String petId;
Pet(String petName, String species, String petId) {
this.petName = petName;
this.species = species;
this.petId = petId;
}
String getPetId() {
return petId;
}
void setPetId(String petId) {
this.petId = petId;
}
}
class Dog extends Pet {
int totalActivities;
Dog(String petName, String species, String petId) {
super(petName, species, petId);
this.totalActivities = 0;
}
void logActivity(int count) {
totalActivities += count;
}
void showDogProfile() {
String Category;
if ("Puppy".equals(super.species)) {
Category = "Small";
} else if ("BullDog".equals(super.species)) {
Category = "Medium";
} else {
Category = "Large";
}
System.out.println("Dog name:" + super.petName + " Species Category:" + Category + " Total Activity Recorded:" + totalActivities);
}
void resetActivities() {
totalActivities = 0;
System.out.println("Activity reset Done");
}
}
class Activity {
void activityType() {
System.out.println("General Activity");
}
}
class WalkingActivity extends Activity {
@Override
void activityType() {
System.out.println("Walking");
}
}
class FeedingActivity extends Activity {
@Override
void activityType() {
System.out.println("Eating");
}
}
class SmartPetMonitoringSystem {
public static void main(String[] args) {
Dog d1 = new Dog("Doggo", "Puppy", "1234");
d1.logActivity(2);
d1.logActivity(3);
d1.showDogProfile();
Activity a1 = new WalkingActivity();
Activity a2 = new FeedingActivity();
a1.activityType();
a2.activityType();
d1.resetActivities();
}
}n. Student Attendance Tracker
java
class Person {
String name;
int yearOfAdmission;
private String personId;
Person(String name, int yearOfAdmission, String personId) {
this.name = name;
this.yearOfAdmission = yearOfAdmission;
this.personId = personId;
}
String getPersonId() {
return personId;
}
void setPersonId(String personId) {
this.personId = personId;
}
}
class Student extends Person {
int totalClasses;
int attendedClasses;
Student(String name, int yearOfAdmission, String personId) {
super(name, yearOfAdmission, personId);
this.totalClasses = 0;
this.attendedClasses = 0;
}
void addClass(int n) {
totalClasses += n;
}
void attendClass(int n) {
if (attendedClasses + n <= totalClasses) {
attendedClasses += n;
} else {
attendedClasses = totalClasses;
}
}
double getAttendancePercentage() {
if (totalClasses == 0) {
return 0.0;
}
return (attendedClasses * 100.0) / totalClasses;
}
void showStatus() {
String admissionCategory;
if (yearOfAdmission <= 2022) {
admissionCategory = "Senior";
} else {
admissionCategory = "Junior";
}
double percentage = getAttendancePercentage();
String eligibility;
if (percentage >= 75) {
eligibility = "Eligible for exam";
} else {
eligibility = "Not eligible";
}
System.out.println("Student Name: " + name);
System.out.println("Admission Category: " + admissionCategory);
System.out.println("Attendance Percentage: " + percentage + "%");
System.out.println("Status: " + eligibility);
}
}
class ReportService {
void generateReport(Person p) {
System.out.println("Generating general report for person...");
}
}
class StudentReportService extends ReportService {
@Override
void generateReport(Person p) {
if (p instanceof Student) {
Student s = (Student) p;
System.out.println("Generating detailed attendance report for student: " + s.name);
System.out.println("Attendance Percentage: " + s.getAttendancePercentage() + "%");
System.out.println("Total Classes: " + s.totalClasses);
System.out.println("Attended Classes: " + s.attendedClasses);
} else {
System.out.println("Generating general report for person...");
}
}
}
class StudentAttendanceTracker {
public static void main(String[] args) {
Student s1 = new Student("Alice", 2021, "STU001");
s1.addClass(20);
s1.attendClass(15);
s1.addClass(10);
s1.attendClass(8);
s1.showStatus();
ReportService reportService = new StudentReportService();
reportService.generateReport(s1);
}
}o. Library Book Borrowing System
java
class LibraryItem {
String title;
int publishYear;
private String itemId;
LibraryItem(String title, int publishYear, String itemId) {
this.title = title;
this.publishYear = publishYear;
this.itemId = itemId;
}
String getItemId() {
return itemId;
}
void setItemId(String itemId) {
this.itemId = itemId;
}
}
class Book extends LibraryItem {
int borrowCount;
boolean isAvailable;
Book(String title, int publishYear, String itemId) {
super(title, publishYear, itemId);
this.borrowCount = 0;
this.isAvailable = true;
}
void borrow() {
if (isAvailable) {
borrowCount++;
isAvailable = false;
System.out.println("Book borrowed successfully");
} else {
System.out.println("Book is currently unavailable");
}
}
void returnBook() {
isAvailable = true;
System.out.println("Book returned");
}
void showStatus() {
String ageCategory;
if (publishYear < 2000) {
ageCategory = "Classic";
} else {
ageCategory = "Modern";
}
String availability;
if (isAvailable) {
availability = "Available";
} else {
availability = "Not Available";
}
System.out.println("Title: " + title);
System.out.println("Age Category: " + ageCategory);
System.out.println("Total Borrow Count: " + borrowCount);
System.out.println("Availability: " + availability);
}
void needsReplacement() {
if (borrowCount >= 50) {
System.out.println("Replacement suggested");
} else {
System.out.println("No replacement needed yet");
}
}
}
class LibraryService {
void processItem(LibraryItem item) {
System.out.println("Processing library item...");
}
}
class BookService extends LibraryService {
@Override
void processItem(LibraryItem item) {
if (item instanceof Book) {
Book b = (Book) item;
b.showStatus();
b.needsReplacement();
} else {
System.out.println("Processing generic library item...");
}
}
}
class LibraryBookBorrowingSystem {
public static void main(String[] args) {
Book b1 = new Book("Java Programming", 2015, "BK001");
b1.borrow();
b1.returnBook();
b1.borrow();
b1.showStatus();
b1.needsReplacement();
LibraryService service = new BookService();
service.processItem(b1);
}
}p. Fitness Center Membership Tracker
java
class Member {
String memberName;
int joinYear;
private String memberId;
Member(String memberName, int joinYear, String memberId) {
this.memberName = memberName;
this.joinYear = joinYear;
this.memberId = memberId;
}
String getMemberId() {
return memberId;
}
void setMemberId(String memberId) {
this.memberId = memberId;
}
}
class GymMember extends Member {
double totalWorkoutHours;
String membershipType;
GymMember(String memberName, int joinYear, String memberId, String membershipType) {
super(memberName, joinYear, memberId);
this.totalWorkoutHours = 0.0;
this.membershipType = membershipType;
}
void addWorkout(double hours) {
if (hours > 0) {
totalWorkoutHours += hours;
}
}
void showStatus() {
int currentYear = 2025;
String durationCategory;
if ((currentYear - joinYear) >= 2) {
durationCategory = "Long-term";
} else {
durationCategory = "New";
}
System.out.println("Member Name: " + memberName);
System.out.println("Membership Duration Category: " + durationCategory);
System.out.println("Membership Type: " + membershipType);
System.out.println("Total Workout Hours: " + totalWorkoutHours);
}
void suggestPlan() {
if (totalWorkoutHours >= 200) {
System.out.println("Excellent engagement");
} else if (totalWorkoutHours >= 100 && totalWorkoutHours < 200) {
System.out.println("Good, keep going");
} else {
System.out.println("Need more regular workouts");
}
}
}
class MembershipService {
void handleMember(Member m) {
System.out.println("Handling generic member...");
}
}
class GymMembershipService extends MembershipService {
@Override
void handleMember(Member m) {
if (m instanceof GymMember) {
GymMember gm = (GymMember) m;
gm.showStatus();
gm.suggestPlan();
} else {
System.out.println("Handling generic member...");
}
}
}
class FitnessCenterMembershipTracker {
public static void main(String[] args) {
GymMember gm1 = new GymMember("John", 2023, "MEM001", "Premium");
gm1.addWorkout(25.5);
gm1.addWorkout(30.0);
gm1.showStatus();
gm1.suggestPlan();
MembershipService service = new GymMembershipService();
service.handleMember(gm1);
}
}q. Online Course Progress Tracker
java
class Course {
String courseName;
int totalModules;
private String courseCode;
Course(String courseName, int totalModules, String courseCode) {
this.courseName = courseName;
this.totalModules = totalModules;
this.courseCode = courseCode;
}
String getCourseCode() {
return courseCode;
}
void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
}
class ProgrammingCourse extends Course {
int completedModules;
String difficultyLevel;
ProgrammingCourse(String courseName, int totalModules, String courseCode, String difficultyLevel) {
super(courseName, totalModules, courseCode);
this.completedModules = 0;
this.difficultyLevel = difficultyLevel;
}
void completeModule(int n) {
if (completedModules + n <= totalModules) {
completedModules += n;
} else {
completedModules = totalModules;
}
}
double getCompletionPercentage() {
if (totalModules == 0) {
return 0.0;
}
return (completedModules * 100.0) / totalModules;
}
void showStatus() {
double percentage = getCompletionPercentage();
String learningStatus;
if (percentage >= 60) {
learningStatus = "On track";
} else {
learningStatus = "Needs attention";
}
System.out.println("Course Name: " + courseName);
System.out.println("Difficulty Level: " + difficultyLevel);
System.out.println("Completion Percentage: " + percentage + "%");
System.out.println("Learning Status: " + learningStatus);
}
void suggestRevision() {
double percentage = getCompletionPercentage();
if (percentage >= 40 && percentage <= 70) {
System.out.println("Revise previous modules");
} else if (percentage > 70) {
System.out.println("Focus on practice problems");
} else {
System.out.println("Start with basics again");
}
}
}
class CourseService {
void reviewCourse(Course c) {
System.out.println("Reviewing generic course...");
}
}
class ProgrammingCourseService extends CourseService {
@Override
void reviewCourse(Course c) {
if (c instanceof ProgrammingCourse) {
ProgrammingCourse pc = (ProgrammingCourse) c;
pc.showStatus();
pc.suggestRevision();
} else {
System.out.println("Reviewing generic course...");
}
}
}
class OnlineCourseProgressTracker {
public static void main(String[] args) {
ProgrammingCourse pc1 = new ProgrammingCourse("Java OOP", 10, "CS101", "Intermediate");
pc1.completeModule(3);
pc1.completeModule(2);
pc1.completeModule(1);
pc1.showStatus();
pc1.suggestRevision();
CourseService service = new ProgrammingCourseService();
service.reviewCourse(pc1);
}
}3. Java Programs
a. Leap year
java
import java.util.Scanner;
class LeapYear {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Year:");
int year = sc.nextInt();
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {
System.out.println("Leap Year");
} else {
System.out.println("Not a leap year");
}
}
}b. Largest of three
java
import java.util.Scanner;
class Largest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 3 values:");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
System.out.println("Largest is:" + Math.max(a, Math.max(b, c)));
}
}c. Fibonacci up to N
java
import java.util.Scanner;
class Fibonacci {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter amount of 'N':");
int n = sc.nextInt();
int a = 0, b = 1;
System.out.println("Fibonacci series:");
for (int i = 0; i < n; i++) {
System.out.println(a + " ");
int next = a + b;
a = b;
b = next;
}
sc.close();
}
}d. Area of circle
java
import java.util.Scanner;
class Area {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter radius of a circle:");
int n = sc.nextInt();
System.out.println("Area of a circle is:" + Math.PI * n * n);
sc.close();
}
}e. All primes up to N (simple sieve-like check)
java
import java.util.Scanner;
class LeapYear {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter range:");
int n = sc.nextInt();
for (int i = 2; i <= n; i++) {
boolean prime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
prime = false;
break;
}
}
if (prime) {
System.out.print(i + " ");
}
}
sc.close();
}
}4. Errors Identified and Corrected Output
Issues:
string author;→ should beString author;- Constructor
Book(String t, String a, int p {→ missing)and parameter names don’t match assignments (pgundefined). - Typo and casing:
tittlevstitle, laterTitleused indisplayDetails(). author = author;self-assigns; should use constructor arg.- Missing semicolon after
System.out.println("Author: " + author). if (pages > "300")compares int to String.return "True";returns String, not boolean.
Corrected class:
java
public class Book {
String title;
String author;
int pages;
Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
void displayDetails() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Pages: " + pages);
}
public boolean isBigBook() {
return pages > 300;
}
public static void main(String[] args) {
Book b = new Book("OOP", "Alice", 350);
b.displayDetails();
System.out.println(b.isBigBook());
}
}Output:
Title: OOP
Author: Alice
Pages: 350
true5. Comparison
Class vs Object
| Class | Object |
|---|---|
| A class is a blueprint or template that defines attributes (variables) and behaviors (methods). | An object is an instance of a class created in memory. |
| It is a logical structure; no memory is allocated until an object is created. | It is a physical entity; memory is allocated when the object is created. |
| Used for defining common features of multiple similar objects. | Used to access and use the properties defined in the class. |
| Defined once; many objects can be created from it. | Each object is independent even if created from the same class. |
| Example: A Car class defines common structure. | Example: myCar = new Car(); creates a specific car object. |
🔹 Summary: Class = Design, Object = Product
Encapsulation vs Abstraction
| Encapsulation | Abstraction |
|---|---|
| Protects data by hiding variables using access modifiers. | Hides internal implementation and shows only essential features. |
| Focuses on data protection. | Focuses on reducing complexity. |
| Achieved using classes, private variables, and getters/setters. | Achieved using abstract classes and interfaces. |
| Implementation is hidden inside the class. | Only the required functions are exposed. |
| Example: making variables private. | Example: List interface hides how ArrayList works. |
🔹 Summary: Encapsulation = Security | Abstraction = Simplicity
Method Overloading vs Method Overriding
| Overloading | Overriding |
|---|---|
| Same method name but different parameters within the same class. | Same method signature but redefined in subclass. |
| Compile‑time polymorphism. | Runtime polymorphism. |
| Increases code readability and flexibility. | Used for extending/changing parent class behavior. |
| Method signature must be different. | Method signature must be same. |
| Example: add(int,int) and add(double,double). | Example: Child overriding parent display() method. |
🔹 Summary: Overloading → Same class | Overriding → Parent–Child classes
Inheritance vs Composition
| Inheritance | Composition |
|---|---|
| Defines an "IS‑A" relationship. | Defines a "HAS‑A" relationship. |
| Strongly coupled (child depends on parent). | Loosely coupled (independent). |
| Changes in parent affect child classes. | Only part objects are affected. |
Achieved using extends keyword. | Achieved by using objects inside another class. |
| Example: Dog is‑a Animal. | Example: Car has‑a Engine. |
🔹 Summary: Inheritance = Reuse by extension | Composition = Reuse by inclusion
Compile-time vs Run-time Polymorphism
| Compile‑time Polymorphism | Run‑time Polymorphism |
|---|---|
| Achieved using method overloading. | Achieved using method overriding. |
| Resolved during compile time. | Resolved during execution time. |
| Faster execution. | Slightly slower. |
| Based on reference type. | Based on object type. |
| Example: multiple constructors. | Example: overridden toString() method. |
🔹 Summary: Compile‑time = Overloading | Runtime = Overriding
IUS Preps - Your Academic Success Partner