0% found this document useful (0 votes)
4 views83 pages

Java OOP Solutions

The document contains a collection of 111 Java programming questions and solutions focused on Object-Oriented Programming (OOP) concepts such as inheritance, method overriding, abstract classes, interfaces, exception handling, and packages. Each question is accompanied by a complete Java program demonstrating the relevant OOP concept. The content is intended for students of the Vidyalankar Institute of Technology, specifically for the B.E. Information Technology program from 2024 to 2028.

Uploaded by

kaustubhwani04
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)
4 views83 pages

Java OOP Solutions

The document contains a collection of 111 Java programming questions and solutions focused on Object-Oriented Programming (OOP) concepts such as inheritance, method overriding, abstract classes, interfaces, exception handling, and packages. Each question is accompanied by a complete Java program demonstrating the relevant OOP concept. The content is intended for students of the Vidyalankar Institute of Technology, specifically for the B.E. Information Technology program from 2024 to 2028.

Uploaded by

kaustubhwani04
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

■ Java OOP Solutions

111 Questions with Complete Java Programs

Inheritance • Method Overriding • Abstract Class • Interface • Exception Handling • Packages

Vidyalankar Institute of Technology | B.E. Information Technology | 2024–2028

Unit 1 – Inheritance 22 Questions

Q1 Write a Java program to create a class Animal with a method speak(). Derive a class Dog from Animal
and override speak() to print "Woof". Create a Dog object and call speak().

■ SOLUTION
class Animal {
void speak() {
[Link]("Animal speaks");
}
}

class Dog extends Animal {


@Override
void speak() {
[Link]("Woof");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 1


Q2 Write a Java program to demonstrate single inheritance. Create a class Vehicle with fields brand and
speed. Derive a class Car that adds a field numDoors and displays all details.

■ SOLUTION
class Vehicle {
String brand;
int speed;
Vehicle(String brand, int speed) {
[Link] = brand;
[Link] = speed;
}
}

class Car extends Vehicle {


int numDoors;
Car(String brand, int speed, int numDoors) {
super(brand, speed);
[Link] = numDoors;
}
void display() {
[Link]("Brand: " + brand);
[Link]("Speed: " + speed + " km/h");
[Link]("Doors: " + numDoors);
}
}

public class Main {


public static void main(String[] args) {
Car c = new Car("Toyota", 180, 4);
[Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 2


Q3 Write a Java program to demonstrate multilevel inheritance. Create classes Vehicle -> Car ->
ElectricCar. Each class adds one field. Display all fields from an ElectricCar object.

■ SOLUTION
class Vehicle {
String brand;
Vehicle(String brand) { [Link] = brand; }
}

class Car extends Vehicle {


int speed;
Car(String brand, int speed) {
super(brand);
[Link] = speed;
}
}

class ElectricCar extends Car {


int batteryRange;
ElectricCar(String brand, int speed, int batteryRange) {
super(brand, speed);
[Link] = batteryRange;
}
void display() {
[Link]("Brand: " + brand);
[Link]("Speed: " + speed + " km/h");
[Link]("Battery Range: " + batteryRange + " km");
}
}

public class Main {


public static void main(String[] args) {
ElectricCar ec = new ElectricCar("Tesla", 250, 500);
[Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 3


Q4 Write a Java program to demonstrate hierarchical inheritance. Create a base class Shape with a
method displayColor(). Derive Circle, Rectangle and Triangle from Shape. Instantiate each and call
displayColor().

■ SOLUTION
class Shape {
String color;
Shape(String color) { [Link] = color; }
void displayColor() {
[Link](getClass().getSimpleName() + " color: " + color);
}
}

class Circle extends Shape { Circle(String c) { super(c); } }


class Rectangle extends Shape { Rectangle(String c) { super(c); } }
class Triangle extends Shape { Triangle(String c) { super(c); } }

public class Main {


public static void main(String[] args) {
new Circle("Red").displayColor();
new Rectangle("Blue").displayColor();
new Triangle("Green").displayColor();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 4


Q5 Write a Java program to create a class Employee with fields name and basicSalary. Derive a class
Manager that adds a field department. Display all information for a Manager object.

■ SOLUTION
class Employee {
String name;
double basicSalary;
Employee(String name, double basicSalary) {
[Link] = name;
[Link] = basicSalary;
}
}

class Manager extends Employee {


String department;
Manager(String name, double basicSalary, String department) {
super(name, basicSalary);
[Link] = department;
}
void display() {
[Link]("Name: " + name);
[Link]("Basic Salary: " + basicSalary);
[Link]("Department: " + department);
}
}

public class Main {


public static void main(String[] args) {
Manager m = new Manager("Alice", 75000, "IT");
[Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 5


Q6 Write a Java program to create a class Person with fields name and age. Derive a class Student that
adds rollNumber and CGPA. Display complete student details using inherited and own fields.

■ SOLUTION
class Person {
String name;
int age;
Person(String name, int age) {
[Link] = name; [Link] = age;
}
}

class Student extends Person {


int rollNumber;
double cgpa;
Student(String name, int age, int rollNumber, double cgpa) {
super(name, age);
[Link] = rollNumber;
[Link] = cgpa;
}
void display() {
[Link]("Name: " + name + ", Age: " + age);
[Link]("Roll No: " + rollNumber + ", CGPA: " + cgpa);
}
}

public class Main {


public static void main(String[] args) {
new Student("Abdulrehman", 18, 101, 9.15).display();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 6


Q7 Write a Java program to demonstrate the use of the super keyword. Create a class Animal with a
constructor that accepts name. Derive Dog from Animal. Use super() in Dog's constructor to pass the
name.

■ SOLUTION
class Animal {
String name;
Animal(String name) {
[Link] = name;
[Link]("Animal created: " + name);
}
}

class Dog extends Animal {


String breed;
Dog(String name, String breed) {
super(name); // calls Animal constructor
[Link] = breed;
[Link]("Dog breed: " + breed);
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog("Bruno", "Labrador");
[Link]("Name: " + [Link] + ", Breed: " + [Link]);
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 7


Q8 Write a Java program to create a class BankAccount with fields accountNumber and balance and a
method deposit(). Derive SavingsAccount that adds interestRate and a method computeInterest().
Display all details.

■ SOLUTION
class BankAccount {
String accountNumber;
double balance;
BankAccount(String accountNumber, double balance) {
[Link] = accountNumber;
[Link] = balance;
}
void deposit(double amount) { balance += amount; }
}

class SavingsAccount extends BankAccount {


double interestRate;
SavingsAccount(String accountNumber, double balance, double interestRate) {
super(accountNumber, balance);
[Link] = interestRate;
}
double computeInterest() { return balance * interestRate / 100; }
void display() {
[Link]("Account: " + accountNumber);
[Link]("Balance: " + balance);
[Link]("Interest Rate: " + interestRate + "%");
[Link]("Interest Earned: " + computeInterest());
}
}

public class Main {


public static void main(String[] args) {
SavingsAccount sa = new SavingsAccount("SA001", 10000, 4.5);
[Link](2000);
[Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 8


Q9 Write a Java program to demonstrate constructor chaining in inheritance. Create a class A with a
parameterized constructor. Derive class B that calls A's constructor using super(). Derive class C from
B.

■ SOLUTION
class A {
A(int x) { [Link]("A constructor, x = " + x); }
}

class B extends A {
B(int x, int y) {
super(x);
[Link]("B constructor, y = " + y);
}
}

class C extends B {
C(int x, int y, int z) {
super(x, y);
[Link]("C constructor, z = " + z);
}
}

public class Main {


public static void main(String[] args) {
C obj = new C(1, 2, 3);
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 9


Q10 Write a Java program to create a class Product with fields productName and price. Derive Electronics
which adds brand. Derive Laptop from Electronics that adds ramSize. Display all fields from a Laptop
object.

■ SOLUTION
class Product {
String productName;
double price;
Product(String productName, double price) {
[Link] = productName; [Link] = price;
}
}

class Electronics extends Product {


String brand;
Electronics(String productName, double price, String brand) {
super(productName, price); [Link] = brand;
}
}

class Laptop extends Electronics {


int ramSize;
Laptop(String productName, double price, String brand, int ramSize) {
super(productName, price, brand); [Link] = ramSize;
}
void display() {
[Link]("Product: " + productName);
[Link]("Price: Rs." + price);
[Link]("Brand: " + brand);
[Link]("RAM: " + ramSize + " GB");
}
}

public class Main {


public static void main(String[] args) {
new Laptop("Laptop Pro", 65000, "Dell", 16).display();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 10


Q11 Write a Java program to create a class Loan with loanAmount and tenure. Derive HomeLoan that adds
propertyValue and computes EMI as (loanAmount / tenure). Display the EMI.

■ SOLUTION
class Loan {
double loanAmount;
int tenure;
Loan(double loanAmount, int tenure) {
[Link] = loanAmount; [Link] = tenure;
}
}

class HomeLoan extends Loan {


double propertyValue;
HomeLoan(double loanAmount, int tenure, double propertyValue) {
super(loanAmount, tenure);
[Link] = propertyValue;
}
double computeEMI() { return loanAmount / tenure; }
void display() {
[Link]("Loan Amount: Rs." + loanAmount);
[Link]("Tenure: " + tenure + " months");
[Link]("Property Value: Rs." + propertyValue);
[Link]("Monthly EMI: Rs." + computeEMI());
}
}

public class Main {


public static void main(String[] args) {
new HomeLoan(1200000, 120, 2500000).display();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 11


Q12 Write a Java program to create a class Staff with name and designation. Derive class Teacher that
adds subject and salary. Override toString() in Teacher to display all details.

■ SOLUTION
class Staff {
String name, designation;
Staff(String name, String designation) {
[Link] = name; [Link] = designation;
}
}

class Teacher extends Staff {


String subject;
double salary;
Teacher(String name, String designation, String subject, double salary) {
super(name, designation);
[Link] = subject; [Link] = salary;
}
@Override
public String toString() {
return "Name: " + name + ", Designation: " + designation +
", Subject: " + subject + ", Salary: " + salary;
}
}

public class Main {


public static void main(String[] args) {
Teacher t = new Teacher("Prof. Sharma", "Lecturer", "Java", 55000);
[Link](t);
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 12


Q13 Write a Java program to demonstrate that a subclass can access protected members of its parent
class. Create a class Account with protected balance. Derive SavingsAccount and access balance
inside a method.

■ SOLUTION
class Account {
protected double balance;
Account(double balance) { [Link] = balance; }
}

class SavingsAccount extends Account {


SavingsAccount(double balance) { super(balance); }
void showBalance() {
// accessing protected member of parent directly
[Link]("Balance: Rs." + balance);
}
void addInterest(double rate) {
balance += balance * rate / 100;
[Link]("Balance after interest: Rs." + balance);
}
}

public class Main {


public static void main(String[] args) {
SavingsAccount sa = new SavingsAccount(10000);
[Link]();
[Link](5);
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 13


Q14 Write a Java program to create a class Appliance with fields brand and powerWatts. Derive
WashingMachine that adds loadCapacityKg. Derive AutomaticWasher that adds hasWiFi. Display all
fields.

■ SOLUTION
class Appliance {
String brand; int powerWatts;
Appliance(String brand, int powerWatts) {
[Link] = brand; [Link] = powerWatts;
}
}

class WashingMachine extends Appliance {


int loadCapacityKg;
WashingMachine(String brand, int powerWatts, int loadCapacityKg) {
super(brand, powerWatts); [Link] = loadCapacityKg;
}
}

class AutomaticWasher extends WashingMachine {


boolean hasWiFi;
AutomaticWasher(String brand, int powerWatts, int load, boolean hasWiFi) {
super(brand, powerWatts, load); [Link] = hasWiFi;
}
void display() {
[Link]("Brand: " + brand);
[Link]("Power: " + powerWatts + "W");
[Link]("Load: " + loadCapacityKg + " kg");
[Link]("WiFi: " + hasWiFi);
}
}

public class Main {


public static void main(String[] args) {
new AutomaticWasher("LG", 2000, 8, true).display();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 14


Q15 Write a Java program to show that private members of a parent class are NOT directly accessible in a
subclass. Use public getter/setter methods in the parent to access them from the subclass.

■ SOLUTION
class Person {
private String name;
private int age;
Person(String name, int age) { [Link] = name; [Link] = age; }
public String getName() { return name; }
public int getAge() { return age; }
public void setName(String name) { [Link] = name; }
}

class Student extends Person {


int rollNo;
Student(String name, int age, int rollNo) {
super(name, age); [Link] = rollNo;
}
void display() {
// name and age accessed via public getters (private = not directly accessible)
[Link]("Name: " + getName());
[Link]("Age: " + getAge());
[Link]("Roll: " + rollNo);
}
}

public class Main {


public static void main(String[] args) {
new Student("Riya", 19, 42).display();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 15


Q16 Write a Java program to create a class Rectangle with length and width. Derive ColoredRectangle that
adds a color field. Override toString() to return "Color: X, Area: Y".

■ SOLUTION
class Rectangle {
double length, width;
Rectangle(double length, double width) {
[Link] = length; [Link] = width;
}
double area() { return length * width; }
}

class ColoredRectangle extends Rectangle {


String color;
ColoredRectangle(double length, double width, String color) {
super(length, width); [Link] = color;
}
@Override
public String toString() {
return "Color: " + color + ", Area: " + area();
}
}

public class Main {


public static void main(String[] args) {
ColoredRectangle cr = new ColoredRectangle(5, 3, "Blue");
[Link](cr);
}
}

Q17 Write a Java program to demonstrate the IS-A relationship. Create Vehicle, Car and Truck classes
using inheritance. Show that a Car IS-A Vehicle and a Truck IS-A Vehicle using instanceof.

■ SOLUTION
class Vehicle {}
class Car extends Vehicle {}
class Truck extends Vehicle {}

public class Main {


public static void main(String[] args) {
Car car = new Car();
Truck truck = new Truck();
[Link]("car instanceof Vehicle: " + (car instanceof Vehicle));
[Link]("truck instanceof Vehicle: " + (truck instanceof Vehicle));
[Link]("car instanceof Truck: " + (car instanceof Truck));
[Link]("car instanceof Car: " + (car instanceof Car));
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 16


Q18 Write a Java program to create a class Student with name, rollNo and marks[]. Derive class
GraduateStudent that adds thesisTitle. Compute and display total marks and thesis details.

■ SOLUTION
class Student {
String name; int rollNo; int[] marks;
Student(String name, int rollNo, int[] marks) {
[Link] = name; [Link] = rollNo; [Link] = marks;
}
int totalMarks() {
int sum = 0;
for (int m : marks) sum += m;
return sum;
}
}

class GraduateStudent extends Student {


String thesisTitle;
GraduateStudent(String name, int rollNo, int[] marks, String thesisTitle) {
super(name, rollNo, marks); [Link] = thesisTitle;
}
void display() {
[Link]("Name: " + name + ", Roll: " + rollNo);
[Link]("Total Marks: " + totalMarks());
[Link]("Thesis: " + thesisTitle);
}
}

public class Main {


public static void main(String[] args) {
new GraduateStudent("Zara", 201, new int[]{85,90,78}, "AI in Healthcare").display();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 17


Q19 Write a Java program to show that constructors are NOT inherited. Create a class A with a
parameterized constructor. Derive class B and show that B must explicitly call super() to use A's
constructor.

■ SOLUTION
class A {
int value;
A(int value) {
[Link] = value;
[Link]("A constructor called, value = " + value);
}
}

class B extends A {
String label;
// B must explicitly call super(value) — it cannot inherit A's constructor
B(int value, String label) {
super(value); // explicit call required
[Link] = label;
[Link]("B constructor called, label = " + label);
}
}

public class Main {


public static void main(String[] args) {
B obj = new B(10, "Test");
[Link]("Value: " + [Link] + ", Label: " + [Link]);
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 18


Q20 Write a Java program to override the toString() method inherited from the Object class. Create a class
Book with title, author and price. Return a formatted string from toString() and print the object.

■ SOLUTION
class Book {
String title, author;
double price;
Book(String title, String author, double price) {
[Link] = title; [Link] = author; [Link] = price;
}
@Override
public String toString() {
return "Book[Title: " + title + ", Author: " + author +
", Price: Rs." + price + "]";
}
}

public class Main {


public static void main(String[] args) {
Book b = new Book("Head First Java", "Kathy Sierra", 499);
[Link](b); // calls toString() automatically
}
}

Q21 Write a Java program to create a class Circle with radius. Derive class Cylinder from Circle that adds
height. Compute area of circle and volume of cylinder using inherited radius.

■ SOLUTION
class Circle {
double radius;
Circle(double radius) { [Link] = radius; }
double area() { return [Link] * radius * radius; }
}

class Cylinder extends Circle {


double height;
Cylinder(double radius, double height) {
super(radius); [Link] = height;
}
double volume() { return area() * height; } // uses inherited area()
}

public class Main {


public static void main(String[] args) {
Cylinder cy = new Cylinder(5, 10);
[Link]("Circle Area: %.2f%n", [Link]());
[Link]("Cylinder Volume: %.2f%n", [Link]());
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 19


Q22 Write a Java program to create a class Account with accountHolder and balance. Derive
CurrentAccount that adds overdraftLimit. A method withdraw() should allow withdrawal up to (balance
+ overdraftLimit).

■ SOLUTION
class Account {
String accountHolder;
double balance;
Account(String accountHolder, double balance) {
[Link] = accountHolder; [Link] = balance;
}
}

class CurrentAccount extends Account {


double overdraftLimit;
CurrentAccount(String holder, double balance, double overdraftLimit) {
super(holder, balance); [Link] = overdraftLimit;
}
void withdraw(double amount) {
if (amount <= balance + overdraftLimit) {
balance -= amount;
[Link]("Withdrawn: Rs." + amount);
[Link]("Remaining Balance: Rs." + balance);
} else {
[Link]("Exceeds overdraft limit! Cannot withdraw.");
}
}
}

public class Main {


public static void main(String[] args) {
CurrentAccount ca = new CurrentAccount("Rohan", 5000, 2000);
[Link](6000);
[Link](2000);
}
}

Unit 2 – Method Overriding 18 Questions

Java OOP Solutions | Vidyalankar Institute of Technology | Page 20


Q23 Write a Java program to demonstrate method overriding. Create a class Shape with a method area()
that prints "Calculating area". Override area() in Circle and Rectangle to compute and print the actual
area.

■ SOLUTION
class Shape {
void area() { [Link]("Calculating area"); }
}

class Circle extends Shape {


double radius;
Circle(double r) { radius = r; }
@Override
void area() {
[Link]("Circle area: %.2f%n", [Link] * radius * radius);
}
}

class Rectangle extends Shape {


double l, w;
Rectangle(double l, double w) { this.l = l; this.w = w; }
@Override
void area() { [Link]("Rectangle area: " + l * w); }
}

public class Main {


public static void main(String[] args) {
Shape s1 = new Circle(7);
Shape s2 = new Rectangle(4, 5);
[Link]();
[Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 21


Q24 Write a Java program to demonstrate runtime polymorphism. Create a base class Animal with method
makeSound(). Override makeSound() in Dog, Cat and Cow. Use an Animal reference to point to each
subclass and call makeSound().

■ SOLUTION
class Animal {
void makeSound() { [Link]("Some sound"); }
}
class Dog extends Animal {
@Override void makeSound() { [Link]("Woof!"); }
}
class Cat extends Animal {
@Override void makeSound() { [Link]("Meow!"); }
}
class Cow extends Animal {
@Override void makeSound() { [Link]("Moo!"); }
}

public class Main {


public static void main(String[] args) {
Animal[] animals = { new Dog(), new Cat(), new Cow() };
for (Animal a : animals) [Link](); // runtime dispatch
}
}

Q25 Write a Java program to demonstrate the use of the @Override annotation. Create a class Vehicle with
method fuelType() returning "Petrol". Override fuelType() in ElectricVehicle to return "Electric".

■ SOLUTION
class Vehicle {
String fuelType() { return "Petrol"; }
}

class ElectricVehicle extends Vehicle {


@Override
String fuelType() { return "Electric"; }
}

public class Main {


public static void main(String[] args) {
Vehicle v1 = new Vehicle();
Vehicle v2 = new ElectricVehicle();
[Link]("Vehicle fuel: " + [Link]());
[Link]("EV fuel: " + [Link]());
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 22


Q26 Write a Java program to demonstrate that a static method CANNOT be overridden (method hiding).
Create a class Parent with static display() and a class Child that defines its own static display(). Show
the behavior.

■ SOLUTION
class Parent {
static void display() { [Link]("Parent static display()"); }
void show() { [Link]("Parent instance show()"); }
}

class Child extends Parent {


static void display() { [Link]("Child static display()"); } // hiding
@Override
void show() { [Link]("Child instance show()"); } // overriding
}

public class Main {


public static void main(String[] args) {
Parent p = new Child();
[Link](); // calls [Link]() — static, resolved at compile time (hiding)
[Link](); // calls [Link]() — instance, resolved at runtime (overriding)
[Link](); // explicitly calls Child's static method
}
}

Q27 Write a Java program to create a class Bank with method getInterestRate() returning 4.0. Override
getInterestRate() in HDFC (returning 6.5) and SBI (returning 5.5). Use a Bank reference to call
getInterestRate() for each.

■ SOLUTION
class Bank {
double getInterestRate() { return 4.0; }
}
class HDFC extends Bank {
@Override double getInterestRate() { return 6.5; }
}
class SBI extends Bank {
@Override double getInterestRate() { return 5.5; }
}

public class Main {


public static void main(String[] args) {
Bank b1 = new HDFC();
Bank b2 = new SBI();
[Link]("HDFC Rate: " + [Link]() + "%");
[Link]("SBI Rate: " + [Link]() + "%");
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 23


Q28 Write a Java program to demonstrate that the access modifier can be widened but NOT narrowed
during method overriding. Show a protected method in parent overridden as public in child.

■ SOLUTION
class Parent {
protected void greet() { [Link]("Hello from Parent"); }
}

class Child extends Parent {


@Override
public void greet() { // widened: protected -> public (allowed)
[Link]("Hello from Child");
}
}

// Narrowing example (compile error — shown as comment):


// class BadChild extends Parent {
// @Override
// private void greet() { } // ERROR: cannot reduce visibility
// }

public class Main {


public static void main(String[] args) {
Parent p = new Child();
[Link]();
Child c = new Child();
[Link](); // accessible as public too
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 24


Q29 Write a Java program to override the toString() method. Create a class Student with name, rollNo and
CGPA. Override toString() to return the details in a formatted string.

■ SOLUTION
class Student {
String name; int rollNo; double cgpa;
Student(String name, int rollNo, double cgpa) {
[Link] = name; [Link] = rollNo; [Link] = cgpa;
}
@Override
public String toString() {
return "Student[Name: " + name + ", Roll: " + rollNo +
", CGPA: " + cgpa + "]";
}
}

public class Main {


public static void main(String[] args) {
Student s = new Student("Abdulrehman", 101, 9.15);
[Link](s);
}
}

Q30 Write a Java program to use [Link]() inside an overriding method. Create a class Printer
with print() that prints "Printing document". Override in LaserPrinter to first call [Link](), then add
"Using laser technology".

■ SOLUTION
class Printer {
void print() { [Link]("Printing document"); }
}

class LaserPrinter extends Printer {


@Override
void print() {
[Link](); // parent behavior
[Link]("Using laser technology");
}
}

public class Main {


public static void main(String[] args) {
LaserPrinter lp = new LaserPrinter();
[Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 25


Q31 Write a Java program to demonstrate method overriding with a covariant return type. Create a class
Animal with a method getAnimal() returning an Animal object. Override in Dog to return a Dog object.

■ SOLUTION
class Animal {
Animal getAnimal() {
[Link]("Returning Animal");
return new Animal();
}
}

class Dog extends Animal {


@Override
Dog getAnimal() { // covariant: Dog is subtype of Animal
[Link]("Returning Dog");
return new Dog();
}
}

public class Main {


public static void main(String[] args) {
Animal a = new Dog();
[Link](); // calls Dog's version at runtime
}
}

Q32 Write a Java program to show runtime polymorphism using an array. Create an array of Shape
references containing Circle, Rectangle and Triangle objects. Iterate and call area() on each.

■ SOLUTION
class Shape { void area() {} }
class Circle extends Shape {
double r; Circle(double r){ this.r=r; }
@Override void area(){ [Link]("Circle area: %.2f%n", [Link]*r*r); }
}
class Rectangle extends Shape {
double l,w; Rectangle(double l,double w){ this.l=l; this.w=w; }
@Override void area(){ [Link]("Rectangle area: "+l*w); }
}
class Triangle extends Shape {
double b,h; Triangle(double b,double h){ this.b=b; this.h=h; }
@Override void area(){ [Link]("Triangle area: "+0.5*b*h); }
}

public class Main {


public static void main(String[] args) {
Shape[] shapes = { new Circle(7), new Rectangle(4,5), new Triangle(6,8) };
for (Shape s : shapes) [Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 26


Q33 Write a Java program to create a class Notification with method send() printing "Sending notification".
Override send() in EmailNotification to print "Sending email" and in SMSNotification to print "Sending
SMS".

■ SOLUTION
class Notification {
void send() { [Link]("Sending notification"); }
}
class EmailNotification extends Notification {
@Override void send() { [Link]("Sending email"); }
}
class SMSNotification extends Notification {
@Override void send() { [Link]("Sending SMS"); }
}

public class Main {


public static void main(String[] args) {
Notification[] n = { new EmailNotification(), new SMSNotification() };
for (Notification x : n) [Link]();
}
}

Q34 Write a Java program to demonstrate that a final method cannot be overridden. Create a class
GovtEmployee with a final method salaryStructure(). Try to override it in a subclass and handle the
result.

■ SOLUTION
class GovtEmployee {
final void salaryStructure() {
[Link]("Fixed pay scale as per 7th Pay Commission");
}
}

class IASOfficer extends GovtEmployee {


// Attempting to override a final method causes a compile-time error:
// @Override
// void salaryStructure() { } // ERROR: cannot override final method
void display() {
salaryStructure(); // can still call it
[Link]("IAS Officer");
}
}

public class Main {


public static void main(String[] args) {
new IASOfficer().display();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 27


Q35 Write a Java program to override the equals() method from the Object class. Create a class Point with
x and y. Two points are equal if both coordinates match. Test with two Point objects.

■ SOLUTION
class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Point)) return false;
Point p = (Point) obj;
return this.x == p.x && this.y == p.y;
}
@Override
public String toString() { return "(" + x + ", " + y + ")"; }
}

public class Main {


public static void main(String[] args) {
Point p1 = new Point(3, 4);
Point p2 = new Point(3, 4);
Point p3 = new Point(1, 2);
[Link]("[Link](p2): " + [Link](p2));
[Link]("[Link](p3): " + [Link](p3));
}
}

Q36 Write a Java program to create a class Logger with method log(String msg). Override in FileLogger to
append "[FILE]" before the message and in ConsoleLogger to append "[CONSOLE]".

■ SOLUTION
class Logger {
void log(String msg) { [Link](msg); }
}
class FileLogger extends Logger {
@Override void log(String msg) { [Link]("[FILE] " + msg); }
}
class ConsoleLogger extends Logger {
@Override void log(String msg) { [Link]("[CONSOLE] " + msg); }
}

public class Main {


public static void main(String[] args) {
Logger[] loggers = { new FileLogger(), new ConsoleLogger() };
for (Logger l : loggers) [Link]("Application started");
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 28


Q37 Write a Java program to demonstrate method overriding in a payroll system. Create abstract class Staff
with abstract method computeSalary(). Override in FullTimeStaff (fixed salary) and PartTimeStaff
(hourly * hours).

■ SOLUTION
abstract class Staff {
String name;
Staff(String name) { [Link] = name; }
abstract double computeSalary();
void display() {
[Link](name + " -> Salary: Rs." + computeSalary());
}
}

class FullTimeStaff extends Staff {


double fixedSalary;
FullTimeStaff(String name, double fixedSalary) {
super(name); [Link] = fixedSalary;
}
@Override double computeSalary() { return fixedSalary; }
}

class PartTimeStaff extends Staff {


double hourlyRate; int hoursWorked;
PartTimeStaff(String name, double hourlyRate, int hoursWorked) {
super(name); [Link] = hourlyRate; [Link] = hoursWorked;
}
@Override double computeSalary() { return hourlyRate * hoursWorked; }
}

public class Main {


public static void main(String[] args) {
Staff[] staff = { new FullTimeStaff("Alice", 50000),
new PartTimeStaff("Bob", 250, 80) };
for (Staff s : staff) [Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 29


Q38 Write a Java program to create a class Game with method start() printing "Game starting". Override in
Chess to print "Chess game starting" and in Cricket to print "Cricket match starting". Use a Game
reference array.

■ SOLUTION
class Game {
void start() { [Link]("Game starting"); }
}
class Chess extends Game { @Override void start() { [Link]("Chess game starting"); } }
class Cricket extends Game { @Override void start() { [Link]("Cricket match
starting"); } }

public class Main {


public static void main(String[] args) {
Game[] games = { new Chess(), new Cricket() };
for (Game g : games) [Link]();
}
}

Q39 Write a Java program to show the difference between method overloading (compile-time
polymorphism) and method overriding (runtime polymorphism) in the same program with a class
Calculator.

■ SOLUTION
class Calculator {
// Overloading — same class, same name, different parameters (compile-time)
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}

class ScientificCalculator extends Calculator {


// Overriding — subclass redefines parent method (runtime)
@Override
int add(int a, int b) {
[Link]("ScientificCalculator add called");
return a + b + 0;
}
}

public class Main {


public static void main(String[] args) {
Calculator c = new Calculator();
[Link]("Overloading: " + [Link](2, 3));
[Link]("Overloading: " + [Link](2.5, 3.5));
[Link]("Overloading: " + [Link](1, 2, 3));

Calculator sc = new ScientificCalculator();


[Link]("Overriding: " + [Link](10, 20)); // runtime dispatch
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 30


Q40 Write a Java program to demonstrate that private methods are NOT overridden. Create a class A with
private method show(). Create class B extending A with its own show(). Show that A's show() is not
overriding.

■ SOLUTION
class A {
private void show() { [Link]("A's private show()"); }
void callShow() { show(); } // calls A's private show
}

class B extends A {
// This is NOT overriding — it is a NEW method in B
void show() { [Link]("B's show() — not an override"); }
}

public class Main {


public static void main(String[] args) {
A obj = new B();
[Link](); // calls A's private show() — B's show() is NOT invoked
B b = new B();
[Link](); // calls B's own show()
}
}

Unit 3 – Abstract Classes 18 Questions

Java OOP Solutions | Vidyalankar Institute of Technology | Page 31


Q41 Write a Java program to create an abstract class Shape with an abstract method area(). Derive Circle
and Rectangle from Shape. Implement area() in each. Create objects of both and display area.

■ SOLUTION
abstract class Shape {
abstract double area();
}

class Circle extends Shape {


double radius;
Circle(double r) { radius = r; }
@Override double area() { return [Link] * radius * radius; }
}

class Rectangle extends Shape {


double l, w;
Rectangle(double l, double w) { this.l = l; this.w = w; }
@Override double area() { return l * w; }
}

public class Main {


public static void main(String[] args) {
Shape s1 = new Circle(7);
Shape s2 = new Rectangle(4, 5);
[Link]("Circle area: %.2f%n", [Link]());
[Link]("Rectangle area: " + [Link]());
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 32


Q42 Write a Java program to create an abstract class Employee with fields name and basicSalary, and
abstract method calculateBonus(). Derive Manager (bonus = 30% of salary) and Clerk (bonus = 10% of
salary). Display bonus for each.

■ SOLUTION
abstract class Employee {
String name; double basicSalary;
Employee(String name, double basicSalary) {
[Link] = name; [Link] = basicSalary;
}
abstract double calculateBonus();
void display() {
[Link](name + " Bonus: Rs." + calculateBonus());
}
}

class Manager extends Employee {


Manager(String name, double salary) { super(name, salary); }
@Override double calculateBonus() { return basicSalary * 0.30; }
}

class Clerk extends Employee {


Clerk(String name, double salary) { super(name, salary); }
@Override double calculateBonus() { return basicSalary * 0.10; }
}

public class Main {


public static void main(String[] args) {
Employee[] emps = { new Manager("Alice", 80000), new Clerk("Bob", 30000) };
for (Employee e : emps) [Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 33


Q43 Write a Java program to demonstrate that an abstract class can have both abstract and concrete
methods. Create abstract class Animal with abstract sound() and concrete breathe(). Derive Dog and
Fish.

■ SOLUTION
abstract class Animal {
abstract void sound(); // abstract
void breathe() { [Link](getClass().getSimpleName() + " breathes"); }
}

class Dog extends Animal { @Override void sound() { [Link]("Woof!"); } }


class Fish extends Animal { @Override void sound() { [Link]("...blub"); } }

public class Main {


public static void main(String[] args) {
Animal[] a = { new Dog(), new Fish() };
for (Animal x : a) { [Link](); [Link](); }
}
}

Q44 Write a Java program to show that an abstract class cannot be instantiated. Attempt to create an object
of an abstract class and handle the compilation outcome.

■ SOLUTION
abstract class AbstractShape {
abstract double area();
}

class ConcreteCircle extends AbstractShape {


double r; ConcreteCircle(double r){ this.r=r; }
@Override double area(){ return [Link]*r*r; }
}

public class Main {


public static void main(String[] args) {
// AbstractShape s = new AbstractShape(); // COMPILE ERROR: cannot instantiate
// Correct usage: use a concrete subclass
AbstractShape s = new ConcreteCircle(5);
[Link]("Area: %.2f%n", [Link]());
[Link]("AbstractShape cannot be instantiated directly.");
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 34


Q45 Write a Java program to create an abstract class Vehicle with abstract method fuelEfficiency(). Derive
Car returning "15 km/l" and Truck returning "8 km/l". Display fuel efficiency using abstract class
reference.

■ SOLUTION
abstract class Vehicle {
abstract String fuelEfficiency();
}
class Car extends Vehicle { @Override String fuelEfficiency() { return "15 km/l"; } }
class Truck extends Vehicle { @Override String fuelEfficiency() { return "8 km/l"; } }

public class Main {


public static void main(String[] args) {
Vehicle[] vehicles = { new Car(), new Truck() };
for (Vehicle v : vehicles)
[Link]([Link]().getSimpleName() + ": " + [Link]());
}
}

Q46 Write a Java program to implement the Template Method pattern. Create abstract class DataProcessor
with concrete method process() that calls abstract methods readData(), processData() and writeData().
Derive CSVProcessor.

■ SOLUTION
abstract class DataProcessor {
abstract void readData();
abstract void processData();
abstract void writeData();
// Template method — defines the skeleton
final void process() {
readData();
processData();
writeData();
}
}

class CSVProcessor extends DataProcessor {


@Override void readData() { [Link]("Reading CSV data"); }
@Override void processData() { [Link]("Processing CSV rows"); }
@Override void writeData() { [Link]("Writing output CSV"); }
}

public class Main {


public static void main(String[] args) {
DataProcessor dp = new CSVProcessor();
[Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 35


Q47 Write a Java program to create an abstract class TaxCalculator with abstract method
computeTax(double income). Derive IncomeTax (tax = 20% of income above 2,50,000) and GST (tax =
18% of income). Display tax.

■ SOLUTION
abstract class TaxCalculator {
abstract double computeTax(double income);
}

class IncomeTax extends TaxCalculator {


@Override
double computeTax(double income) {
return income > 250000 ? (income - 250000) * 0.20 : 0;
}
}

class GST extends TaxCalculator {


@Override double computeTax(double income) { return income * 0.18; }
}

public class Main {


public static void main(String[] args) {
TaxCalculator it = new IncomeTax();
TaxCalculator gst = new GST();
double income = 500000;
[Link]("Income Tax: Rs." + [Link](income));
[Link]("GST: Rs." + [Link](income));
}
}

Q48 Write a Java program to create an abstract class Appliance with abstract method powerConsumption().
Derive AC (2000W) and Fridge (350W). Print consumption for both using an Appliance reference.

■ SOLUTION
abstract class Appliance {
abstract int powerConsumption();
}
class AC extends Appliance { @Override int powerConsumption() { return 2000; } }
class Fridge extends Appliance { @Override int powerConsumption() { return 350; } }

public class Main {


public static void main(String[] args) {
Appliance[] apps = { new AC(), new Fridge() };
for (Appliance a : apps)
[Link]([Link]().getSimpleName() +
": " + [Link]() + "W");
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 36


Q49 Write a Java program to demonstrate that an abstract class can have a constructor. Create abstract
class Shape with a constructor that sets color. Derive Circle that calls super(color) and also sets radius.

■ SOLUTION
abstract class Shape {
String color;
Shape(String color) {
[Link] = color;
[Link]("Shape constructor: color = " + color);
}
abstract double area();
}

class Circle extends Shape {


double radius;
Circle(String color, double radius) {
super(color); // abstract class constructor called
[Link] = radius;
}
@Override double area() { return [Link] * radius * radius; }
void display() {
[Link]("Circle [%s] area: %.2f%n", color, area());
}
}

public class Main {


public static void main(String[] args) {
new Circle("Red", 5).display();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 37


Q50 Write a Java program to show that if a subclass does NOT implement all abstract methods of its
parent, the subclass must also be declared abstract. Demonstrate with Shape -> Polygon -> Triangle.

■ SOLUTION
abstract class Shape {
abstract double area();
abstract double perimeter();
}

// Polygon implements perimeter() but NOT area() — must be abstract


abstract class Polygon extends Shape {
int sides;
Polygon(int sides) { [Link] = sides; }
@Override
public double perimeter() {
[Link]("Generic polygon perimeter");
return 0;
}
// area() still not implemented — Polygon remains abstract
}

class Triangle extends Polygon {


double a, b, c;
Triangle(double a, double b, double c) {
super(3); this.a = a; this.b = b; this.c = c;
}
@Override public double area() {
double s = (a + b + c) / 2;
return [Link](s * (s - a) * (s - b) * (s - c));
}
@Override public double perimeter() { return a + b + c; }
}

public class Main {


public static void main(String[] args) {
Triangle t = new Triangle(3, 4, 5);
[Link]("Area: %.2f, Perimeter: %.1f%n", [Link](), [Link]());
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 38


Q51 Write a Java program to create an abstract class Discount with abstract method
computeDiscount(double price). Derive FestivalDiscount (20% off) and ClearanceSale (50% off).
Display discounted price.

■ SOLUTION
abstract class Discount {
abstract double computeDiscount(double price);
void display(double price) {
double disc = computeDiscount(price);
[Link]("%s: Original Rs.%.0f -> After Discount Rs.%.0f%n",
getClass().getSimpleName(), price, price - disc);
}
}
class FestivalDiscount extends Discount {
@Override double computeDiscount(double price) { return price * 0.20; }
}
class ClearanceSale extends Discount {
@Override double computeDiscount(double price) { return price * 0.50; }
}

public class Main {


public static void main(String[] args) {
Discount[] discounts = { new FestivalDiscount(), new ClearanceSale() };
for (Discount d : discounts) [Link](1000);
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 39


Q52 Write a Java program to create an abstract class Report with a template method generate() that calls
abstract methods fetchData() and formatData(), and a concrete method printReport(). Derive
SalesReport.

■ SOLUTION
abstract class Report {
abstract void fetchData();
abstract void formatData();
void printReport() { [Link]("Printing formatted report..."); }
final void generate() { // template method
fetchData();
formatData();
printReport();
}
}

class SalesReport extends Report {


@Override void fetchData() { [Link]("Fetching sales data from DB"); }
@Override void formatData() { [Link]("Formatting into monthly table"); }
}

public class Main {


public static void main(String[] args) {
Report r = new SalesReport();
[Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 40


Q53 Write a Java program to demonstrate polymorphism using abstract class reference. Create abstract
class Geometry with abstract method perimeter(). Derive Circle, Rectangle and Triangle. Store in a
Geometry array and call perimeter().

■ SOLUTION
abstract class Geometry { abstract double perimeter(); }

class Circle extends Geometry {


double r; Circle(double r){ this.r=r; }
@Override double perimeter(){ return 2*[Link]*r; }
}
class Rectangle extends Geometry {
double l,w; Rectangle(double l,double w){ this.l=l; this.w=w; }
@Override double perimeter(){ return 2*(l+w); }
}
class Triangle extends Geometry {
double a,b,c; Triangle(double a,double b,double c){ this.a=a;this.b=b;this.c=c; }
@Override double perimeter(){ return a+b+c; }
}

public class Main {


public static void main(String[] args) {
Geometry[] g = { new Circle(7), new Rectangle(4,5), new Triangle(3,4,5) };
for (Geometry x : g)
[Link]("%s perimeter: %.2f%n", [Link]().getSimpleName(), [Link]());
}
}

Q54 Write a Java program to show an abstract class can have static methods. Create abstract class
MathUtils with static method square(int n). Call square() without creating any object.

■ SOLUTION
abstract class MathUtils {
static int square(int n) { return n * n; }
static int cube(int n) { return n * n * n; }
}

public class Main {


public static void main(String[] args) {
[Link]("Square of 5: " + [Link](5));
[Link]("Cube of 3: " + [Link](3));
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 41


Q55 Write a Java program to create an abstract class BankAccount with abstract method
calculateInterest(). Derive SavingsAccount (4% per year) and FixedDeposit (7% per year). Display
interest for a given principal.

■ SOLUTION
abstract class BankAccount {
double principal;
BankAccount(double principal) { [Link] = principal; }
abstract double calculateInterest();
void display() {
[Link]("%s -> Principal: Rs.%.0f, Interest: Rs.%.2f%n",
getClass().getSimpleName(), principal, calculateInterest());
}
}
class SavingsAccount extends BankAccount {
SavingsAccount(double p) { super(p); }
@Override double calculateInterest() { return principal * 4 / 100; }
}
class FixedDeposit extends BankAccount {
FixedDeposit(double p) { super(p); }
@Override double calculateInterest() { return principal * 7 / 100; }
}

public class Main {


public static void main(String[] args) {
BankAccount[] accounts = { new SavingsAccount(50000), new FixedDeposit(50000) };
for (BankAccount a : accounts) [Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 42


Q56 Write a Java program to create an abstract class Notification with abstract method send() and a
concrete method schedule(String time) that prints "Scheduled at: time". Derive PushNotification and
EmailAlert.

■ SOLUTION
abstract class Notification {
abstract void send();
void schedule(String time) { [Link]("Scheduled at: " + time); }
}
class PushNotification extends Notification {
@Override void send() { [Link]("Sending push notification"); }
}
class EmailAlert extends Notification {
@Override void send() { [Link]("Sending email alert"); }
}

public class Main {


public static void main(String[] args) {
Notification[] n = { new PushNotification(), new EmailAlert() };
for (Notification x : n) { [Link](); [Link]("10:00 AM"); }
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 43


Q57 Write a Java program to demonstrate that an abstract class can implement an interface. Create
interface Printable with print(). Create abstract class Document implementing Printable partially. Derive
Invoice that completes it.

■ SOLUTION
interface Printable {
void print();
void preview();
}

// Abstract class implements interface but leaves preview() abstract


abstract class Document implements Printable {
String title;
Document(String title) { [Link] = title; }
@Override public void print() { [Link]("Printing: " + title); }
// preview() left abstract — subclass must implement
}

class Invoice extends Document {


double amount;
Invoice(String title, double amount) { super(title); [Link] = amount; }
@Override public void preview() {
[Link]("Preview: " + title + " | Amount: Rs." + amount);
}
}

public class Main {


public static void main(String[] args) {
Invoice inv = new Invoice("INV-001", 5000);
[Link]();
[Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 44


Q58 Write a Java program to create an abstract class Food with fields name and calories and abstract
method nutritionInfo(). Derive Fruit and Junk. Override nutritionInfo() to display relevant details.

■ SOLUTION
abstract class Food {
String name; int calories;
Food(String name, int calories) { [Link] = name; [Link] = calories; }
abstract void nutritionInfo();
}

class Fruit extends Food {


double vitaminsGram;
Fruit(String name, int cal, double vitaminsGram) {
super(name, cal); [Link] = vitaminsGram;
}
@Override void nutritionInfo() {
[Link](name + " | Calories: " + calories +
" | Vitamins: " + vitaminsGram + "g (Healthy)");
}
}

class Junk extends Food {


double fatGram;
Junk(String name, int cal, double fatGram) {
super(name, cal); [Link] = fatGram;
}
@Override void nutritionInfo() {
[Link](name + " | Calories: " + calories +
" | Fat: " + fatGram + "g (Unhealthy)");
}
}

public class Main {


public static void main(String[] args) {
Food[] foods = { new Fruit("Apple", 95, 0.4), new Junk("Burger", 540, 28.5) };
for (Food f : foods) [Link]();
}
}

Unit 4 – Interfaces 18 Questions

Java OOP Solutions | Vidyalankar Institute of Technology | Page 45


Q59 Write a Java program to create an interface Drawable with a method draw(). Implement Drawable in
Circle and Rectangle classes. Create objects of both and call draw().

■ SOLUTION
interface Drawable { void draw(); }

class Circle implements Drawable { public void draw() { [Link]("Drawing Circle"); } }


class Rectangle implements Drawable { public void draw() { [Link]("Drawing
Rectangle"); } }

public class Main {


public static void main(String[] args) {
Drawable[] shapes = { new Circle(), new Rectangle() };
for (Drawable d : shapes) [Link]();
}
}

Q60 Write a Java program to demonstrate multiple interface implementation. Create interfaces Flyable with
fly() and Swimmable with swim(). Create a class Duck that implements both and define fly() and
swim().

■ SOLUTION
interface Flyable { void fly(); }
interface Swimmable { void swim(); }

class Duck implements Flyable, Swimmable {


public void fly() { [Link]("Duck is flying"); }
public void swim() { [Link]("Duck is swimming"); }
}

public class Main {


public static void main(String[] args) {
Duck d = new Duck();
[Link]();
[Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 46


Q61 Write a Java program to create an interface Payable with method computePay(). Implement in
FullTimeEmployee (fixed monthly salary) and Freelancer (hourly rate * hours worked). Display pay for
both.

■ SOLUTION
interface Payable { double computePay(); }

class FullTimeEmployee implements Payable {


String name; double monthlySalary;
FullTimeEmployee(String name, double salary){ [Link]=name; monthlySalary=salary; }
public double computePay() { return monthlySalary; }
}

class Freelancer implements Payable {


String name; double hourlyRate; int hours;
Freelancer(String name, double rate, int hours){ [Link]=name; hourlyRate=rate;
[Link]=hours; }
public double computePay() { return hourlyRate * hours; }
}

public class Main {


public static void main(String[] args) {
Payable[] p = { new FullTimeEmployee("Alice", 50000),
new Freelancer("Bob", 500, 80) };
for (Payable x : p)
[Link]([Link]().getSimpleName() + " pay: Rs." + [Link]());
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 47


Q62 Write a Java program to create an interface Resizable with methods scaleUp(double factor) and
scaleDown(double factor). Implement in Image class that stores width and height. Display dimensions
after scaling.

■ SOLUTION
interface Resizable {
void scaleUp(double factor);
void scaleDown(double factor);
}

class Image implements Resizable {


double width, height;
Image(double w, double h) { width = w; height = h; }
public void scaleUp(double f) { width *= f; height *= f; print("ScaleUp"); }
public void scaleDown(double f) { width /= f; height /= f; print("ScaleDown"); }
void print(String op) {
[Link]("%s -> Width: %.1f, Height: %.1f%n", op, width, height);
}
}

public class Main {


public static void main(String[] args) {
Image img = new Image(800, 600);
[Link](1.5);
[Link](2);
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 48


Q63 Write a Java program to demonstrate interface with a default method (Java 8). Create interface
Greeting with default method sayHello() printing "Hello!". Implement in English and French classes.
French overrides sayHello() to print "Bonjour!".

■ SOLUTION
interface Greeting {
default void sayHello() { [Link]("Hello!"); }
}

class English implements Greeting {} // uses default

class French implements Greeting {


@Override
public void sayHello() { [Link]("Bonjour!"); }
}

public class Main {


public static void main(String[] args) {
Greeting g1 = new English();
Greeting g2 = new French();
[Link]();
[Link]();
}
}

Q64 Write a Java program to demonstrate a static method in an interface (Java 8). Create interface
MathUtils with static method cube(int n). Call cube() using the interface name.

■ SOLUTION
interface MathUtils {
static int cube(int n) { return n * n * n; }
static int square(int n) { return n * n; }
}

public class Main {


public static void main(String[] args) {
[Link]("Cube of 4: " + [Link](4));
[Link]("Square of 5: " + [Link](5));
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 49


Q65 Write a Java program to demonstrate interface inheritance. Create interface Movable with move().
Create interface Flyable extending Movable that adds fly(). Implement Flyable in class Drone.

■ SOLUTION
interface Movable { void move(); }
interface Flyable extends Movable { void fly(); }

class Drone implements Flyable {


public void move() { [Link]("Drone moving horizontally"); }
public void fly() { [Link]("Drone flying upward"); }
}

public class Main {


public static void main(String[] args) {
Drone d = new Drone();
[Link]();
[Link]();
Movable m = new Drone();
[Link]();
}
}

Q66 Write a Java program to create a functional interface Calculator with method operate(int a, int b). Use
lambda expressions to create Add, Subtract and Multiply behaviors. Display results.

■ SOLUTION
@FunctionalInterface
interface Calculator {
int operate(int a, int b);
}

public class Main {


public static void main(String[] args) {
Calculator add = (a, b) -> a + b;
Calculator subtract = (a, b) -> a - b;
Calculator multiply = (a, b) -> a * b;

[Link]("10 + 3 = " + [Link](10, 3));


[Link]("10 - 3 = " + [Link](10, 3));
[Link]("10 * 3 = " + [Link](10, 3));
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 50


Q67 Write a Java program to create interfaces Printable with print() and Scannable with scan(). Implement
both in class MultifunctionPrinter. Call both methods on a MultifunctionPrinter object.

■ SOLUTION
interface Printable { void print(); }
interface Scannable { void scan(); }

class MultifunctionPrinter implements Printable, Scannable {


public void print() { [Link]("Printing document..."); }
public void scan() { [Link]("Scanning document..."); }
}

public class Main {


public static void main(String[] args) {
MultifunctionPrinter mfp = new MultifunctionPrinter();
[Link]();
[Link]();
}
}

Q68 Write a Java program to demonstrate interface as a type. Write a method printAll(Printable p) that
accepts a Printable parameter and calls [Link](). Pass different Printable objects to this method.

■ SOLUTION
interface Printable { void print(); }

class PDFDocument implements Printable { public void print() { [Link]("Printing PDF");


} }
class WordDocument implements Printable { public void print() { [Link]("Printing Word
Doc"); } }

public class Main {


static void printAll(Printable p) { [Link](); }

public static void main(String[] args) {


printAll(new PDFDocument());
printAll(new WordDocument());
printAll(() -> [Link]("Printing via lambda"));
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 51


Q69 Write a Java program to create an interface DatabaseConnectable with methods connect() and
disconnect(). Implement in MySQLDatabase and MongoDatabase with appropriate messages.

■ SOLUTION
interface DatabaseConnectable {
void connect();
void disconnect();
}

class MySQLDatabase implements DatabaseConnectable {


public void connect() { [Link]("MySQL: Connected to database"); }
public void disconnect() { [Link]("MySQL: Connection closed"); }
}

class MongoDatabase implements DatabaseConnectable {


public void connect() { [Link]("MongoDB: Connected to cluster"); }
public void disconnect() { [Link]("MongoDB: Disconnected from cluster"); }
}

public class Main {


public static void main(String[] args) {
DatabaseConnectable[] dbs = { new MySQLDatabase(), new MongoDatabase() };
for (DatabaseConnectable db : dbs) { [Link](); [Link](); }
}
}

Q70 Write a Java program to demonstrate how a conflict between two default methods from different
interfaces is resolved. Create interface A with default greet(), interface B with default greet().
Implement both in class C and override greet().

■ SOLUTION
interface A { default void greet() { [Link]("Hello from A"); } }
interface B { default void greet() { [Link]("Hello from B"); } }

class C implements A, B {
@Override
public void greet() { // must override to resolve conflict
[Link](); // optionally call one parent's default
[Link]("Hello from C (conflict resolved)");
}
}

public class Main {


public static void main(String[] args) { new C().greet(); }
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 52


Q71 Write a Java program to create an interface Sortable with method sort(int[] arr). Implement in
BubbleSorter and SelectionSorter. Display sorted array using both implementations.

■ SOLUTION
import [Link];
interface Sortable { void sort(int[] arr); }

class BubbleSorter implements Sortable {


public void sort(int[] arr) {
int n = [Link];
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1]) { int t=arr[j]; arr[j]=arr[j+1]; arr[j+1]=t; }
}
}
class SelectionSorter implements Sortable {
public void sort(int[] arr) {
int n = [Link];
for (int i = 0; i < n-1; i++) {
int min = i;
for (int j = i+1; j < n; j++) if (arr[j] < arr[min]) min = j;
int t = arr[i]; arr[i] = arr[min]; arr[min] = t;
}
}
}

public class Main {


public static void main(String[] args) {
int[] a1 = {64,34,25,12,22};
int[] a2 = {64,34,25,12,22};
new BubbleSorter().sort(a1);
new SelectionSorter().sort(a2);
[Link]("Bubble: " + [Link](a1));
[Link]("Selection: " + [Link](a2));
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 53


Q72 Write a Java program to create interfaces Cookable with cook() and Serveable with serve(). Create
class Chef implementing both. Add a method prepareMeal() that calls cook() then serve().

■ SOLUTION
interface Cookable { void cook(); }
interface Serveable { void serve(); }

class Chef implements Cookable, Serveable {


String dish;
Chef(String dish) { [Link] = dish; }
public void cook() { [Link]("Cooking: " + dish); }
public void serve() { [Link]("Serving: " + dish); }
void prepareMeal() { cook(); serve(); }
}

public class Main {


public static void main(String[] args) {
new Chef("Biryani").prepareMeal();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 54


Q73 Write a Java program to implement a Comparable-style interface Rankable with method
compareTo(Rankable other). Implement in Product class (compare by price). Sort two products and
display in ascending order.

■ SOLUTION
interface Rankable { int compareTo(Rankable other); }

class Product implements Rankable {


String name; double price;
Product(String name, double price) { [Link] = name; [Link] = price; }
public int compareTo(Rankable other) {
return [Link]([Link], ((Product) other).price);
}
public String toString() { return name + " Rs." + price; }
}

public class Main {


public static void main(String[] args) {
Product[] products = {
new Product("Laptop", 65000),
new Product("Phone", 15000),
new Product("Watch", 3000)
};
// Bubble sort using Rankable compareTo
for (int i = 0; i < [Link] - 1; i++)
for (int j = 0; j < [Link] - i - 1; j++)
if (products[j].compareTo(products[j+1]) > 0) {
Product tmp = products[j]; products[j] = products[j+1]; products[j+1] = tmp;
}
[Link]("Products sorted by price:");
for (Product p : products) [Link](p);
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 55


Q74 Write a Java program to demonstrate the difference between an interface and an abstract class.
Create an abstract class AbstractShape and an interface ShapeInterface both having area(). Show
differences in implementation.

■ SOLUTION
interface ShapeInterface {
double area(); // implicitly public abstract
default void describe() { [Link]("I am a shape (interface)"); }
}

abstract class AbstractShape {


String color;
AbstractShape(String color) { [Link] = color; } // constructor allowed
abstract double area();
void describe() { [Link]("I am a " + color + " shape (abstract class)"); }
}

class CircleI extends AbstractShape implements ShapeInterface {


double r;
CircleI(String color, double r) { super(color); this.r = r; }
public double area() { return [Link] * r * r; }
}

public class Main {


public static void main(String[] args) {
CircleI c = new CircleI("Red", 5);
[Link](); // abstract class method
[Link]("Area: %.2f%n", [Link]());
ShapeInterface si = c;
[Link](); // interface default method (same override)
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 56


Q75 Write a Java program to create an interface Lendable with lend(String borrower) and an interface
Returnable with returnItem(). Implement both in class LibraryBook. Simulate lend and return
operations.

■ SOLUTION
interface Lendable { void lend(String borrower); }
interface Returnable { void returnItem(); }

class LibraryBook implements Lendable, Returnable {


String title; String currentBorrower = null;
LibraryBook(String title) { [Link] = title; }
public void lend(String borrower) {
if (currentBorrower == null) {
currentBorrower = borrower;
[Link](""" + title + "" lent to " + borrower);
} else [Link]("Already lent to " + currentBorrower);
}
public void returnItem() {
[Link](""" + title + "" returned by " + currentBorrower);
currentBorrower = null;
}
}

public class Main {


public static void main(String[] args) {
LibraryBook book = new LibraryBook("Clean Code");
[Link]("Alice");
[Link]("Bob"); // should reject
[Link]();
[Link]("Bob"); // now available
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 57


Q76 Write a Java program to create a mini-project: interface Taxable with computeTax(double amount),
interface Discountable with computeDiscount(double amount). Class Product implements both. Display
final price after tax and discount.

■ SOLUTION
interface Taxable { double computeTax(double amount); }
interface Discountable { double computeDiscount(double amount); }

class Product implements Taxable, Discountable {


String name; double basePrice;
Product(String name, double basePrice) { [Link]=name; [Link]=basePrice; }
public double computeTax(double amount) { return amount * 0.18; }
public double computeDiscount(double amount) { return amount * 0.10; }
void displayFinalPrice() {
double discount = computeDiscount(basePrice);
double priceAfterDiscount = basePrice - discount;
double tax = computeTax(priceAfterDiscount);
double finalPrice = priceAfterDiscount + tax;
[Link]("%s | Base: Rs.%.0f | Discount(10%%): Rs.%.0f | " +
"Tax(18%%): Rs.%.2f | Final: Rs.%.2f%n",
name, basePrice, discount, tax, finalPrice);
}
}

public class Main {


public static void main(String[] args) {
new Product("Laptop", 60000).displayFinalPrice();
new Product("Phone", 20000).displayFinalPrice();
}
}

Unit 5 – Exception Handling 20 Questions

Java OOP Solutions | Vidyalankar Institute of Technology | Page 58


Q77 Write a Java program to handle ArithmeticException. Accept two integers from the user. Divide the first
by the second. If the second is zero, catch the exception and print an appropriate message.

■ SOLUTION
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter dividend: "); int a = [Link]();
[Link]("Enter divisor: "); int b = [Link]();
try {
int result = a / b;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero. " + [Link]());
}
}
}

Q78 Write a Java program to handle ArrayIndexOutOfBoundsException. Create an array of size 5. Try to
access index 10. Catch the exception and display a meaningful error message.

■ SOLUTION
public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
try {
[Link]("Accessing index 10: " + arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Array index out of bounds! " + [Link]());
[Link]("Valid indices are 0 to " + ([Link] - 1));
}
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 59


Q79 Write a Java program to handle NumberFormatException. Accept a string from the user and try to
parse it as an integer using [Link](). Catch the exception if the string is not a valid integer.

■ SOLUTION
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
String input = [Link]();
try {
int num = [Link](input);
[Link]("Parsed integer: " + num);
} catch (NumberFormatException e) {
[Link]("Error: "" + input + "" is not a valid integer.");
}
}
}

Q80 Write a Java program to create a custom checked exception InsufficientFundsException. Create a
BankAccount class. Throw InsufficientFundsException when withdrawal amount exceeds balance.
Handle it in main.

■ SOLUTION
class InsufficientFundsException extends Exception {
InsufficientFundsException(String msg) { super(msg); }
}

class BankAccount {
double balance;
BankAccount(double balance) { [Link] = balance; }
void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance)
throw new InsufficientFundsException(
"Insufficient funds! Balance: " + balance + ", Requested: " + amount);
balance -= amount;
[Link]("Withdrawn Rs." + amount + ". New balance: Rs." + balance);
}
}

public class Main {


public static void main(String[] args) {
BankAccount acc = new BankAccount(5000);
try {
[Link](3000);
[Link](4000); // will throw exception
} catch (InsufficientFundsException e) {
[Link]("Caught: " + [Link]());
}
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 60


Q81 Write a Java program to create a custom unchecked exception InvalidAgeException. In a class Person,
throw InvalidAgeException in the setAge() method if age is less than 0 or greater than 150.

■ SOLUTION
class InvalidAgeException extends RuntimeException {
InvalidAgeException(String msg) { super(msg); }
}

class Person {
String name; int age;
Person(String name) { [Link] = name; }
void setAge(int age) {
if (age < 0 || age > 150)
throw new InvalidAgeException("Invalid age: " + age + ". Must be 0-150.");
[Link] = age;
}
void display() { [Link](name + ", Age: " + age); }
}

public class Main {


public static void main(String[] args) {
Person p = new Person("Alice");
try {
[Link](25); [Link]();
[Link](200); // throws
} catch (InvalidAgeException e) {
[Link]("Caught: " + [Link]());
}
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 61


Q82 Write a Java program to demonstrate the use of the finally block. Open a simulated file (String
resource). In try block perform an operation that throws an exception. Print "Resource closed" in finally.

■ SOLUTION
public class Main {
static void processFile(String filename) {
String resource = null;
try {
resource = "File: " + filename;
[Link]("Opened " + resource);
int x = 10 / 0; // simulate exception
[Link]("Processing...");
} catch (ArithmeticException e) {
[Link]("Error during processing: " + [Link]());
} finally {
[Link]("Resource closed"); // always executes
}
}
public static void main(String[] args) {
processFile("[Link]");
}
}

Q83 Write a Java program to demonstrate multi-catch (Java 7+). Write code that may throw either
NumberFormatException or ArrayIndexOutOfBoundsException. Catch both in a single catch block.

■ SOLUTION
public class Main {
public static void main(String[] args) {
String[] data = {"10", "20", "abc"};
for (int i = 0; i <= 4; i++) {
try {
int val = [Link](data[i]); // may throw NumberFormat or AIOOBE
[Link]("Value: " + val);
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
[Link]("Caught (" + [Link]().getSimpleName() + "): " + [Link]());
}
}
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 62


Q84 Write a Java program to demonstrate the difference between throw and throws. Create a method
checkMarks(int marks) that throws InvalidMarksException if marks < 0 or > 100. Declare throws in the
method signature.

■ SOLUTION
class InvalidMarksException extends Exception {
InvalidMarksException(String msg) { super(msg); }
}

public class Main {


// 'throws' declares the exception in signature
static void checkMarks(int marks) throws InvalidMarksException {
if (marks < 0 || marks > 100)
throw new InvalidMarksException("Marks " + marks + " out of range [0,100]");
[Link]("Valid marks: " + marks);
}
public static void main(String[] args) {
int[] tests = {85, -5, 110, 60};
for (int m : tests) {
try {
checkMarks(m);
} catch (InvalidMarksException e) {
[Link]("Caught: " + [Link]());
}
}
}
}

Q85 Write a Java program to demonstrate exception propagation. Create three methods: method1() calls
method2(), method2() calls method3(). method3() throws an ArithmeticException. Catch it only in
method1().

■ SOLUTION
public class Main {
static void method3() { int r = 10 / 0; } // throws ArithmeticException
static void method2() { method3(); } // propagates
static void method1() {
try { method2(); }
catch (ArithmeticException e) {
[Link]("Caught in method1: " + [Link]());
}
}
public static void main(String[] args) { method1(); }
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 63


Q86 Write a Java program to create a custom exception InvalidPINException. In a class ATM, throw
InvalidPINException if the entered PIN does not match the stored PIN. Handle it in main and allow 3
attempts.

■ SOLUTION
class InvalidPINException extends Exception {
InvalidPINException(String msg) { super(msg); }
}

class ATM {
private int storedPIN = 1234;
void validatePIN(int pin) throws InvalidPINException {
if (pin != storedPIN) throw new InvalidPINException("Wrong PIN: " + pin);
[Link]("PIN accepted. Welcome!");
}
}

public class Main {


public static void main(String[] args) {
ATM atm = new ATM();
int[] attempts = {1111, 9999, 1234};
for (int i = 0; i < [Link]; i++) {
try {
[Link]("Attempt " + (i+1) + ": ");
[Link](attempts[i]);
break;
} catch (InvalidPINException e) {
[Link]("Error: " + [Link]());
}
}
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 64


Q87 Write a Java program to create a class StudentGrade. Accept marks from the user. Throw a custom
InvalidMarksException if marks are not in range 0-100. Display grade (A/B/C/F) for valid marks.

■ SOLUTION
import [Link];
class InvalidMarksException extends Exception {
InvalidMarksException(String msg) { super(msg); }
}

public class Main {


static String getGrade(int marks) {
if (marks >= 90) return "A";
if (marks >= 75) return "B";
if (marks >= 50) return "C";
return "F";
}
public static void main(String[] args) throws InvalidMarksException {
Scanner sc = new Scanner([Link]);
[Link]("Enter marks: ");
int marks = [Link]();
if (marks < 0 || marks > 100)
throw new InvalidMarksException("Marks must be between 0 and 100. Got: " + marks);
[Link]("Grade: " + getGrade(marks));
}
}

Q88 Write a Java program to demonstrate try-with-resources (Java 7+). Create a class FileResource
implementing AutoCloseable. Use it inside a try-with-resources block. Show that close() is called
automatically.

■ SOLUTION
class FileResource implements AutoCloseable {
String name;
FileResource(String name) {
[Link] = name;
[Link]("Opening resource: " + name);
}
void read() { [Link]("Reading from: " + name); }
@Override
public void close() { [Link]("Closing resource: " + name); }
}

public class Main {


public static void main(String[] args) {
try (FileResource fr = new FileResource("[Link]")) {
[Link]();
// close() called automatically when try block exits
}
[Link]("After try-with-resources block");
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 65


Q89 Write a Java program to demonstrate exception chaining. Catch a low-level exception
(NumberFormatException) and wrap it in a higher-level custom exception AppException using the
cause constructor.

■ SOLUTION
class AppException extends Exception {
AppException(String msg, Throwable cause) { super(msg, cause); }
}

public class Main {


static int parseConfig(String value) throws AppException {
try {
return [Link](value);
} catch (NumberFormatException e) {
throw new AppException("Failed to parse config value: " + value, e);
}
}
public static void main(String[] args) {
try {
int timeout = parseConfig("abc");
} catch (AppException e) {
[Link]("AppException: " + [Link]());
[Link]("Caused by: " + [Link]());
}
}
}

Q90 Write a Java program to re-throw an exception. In a method processData(), catch an


ArithmeticException, log the message, then re-throw it as a RuntimeException to the caller.

■ SOLUTION
public class Main {
static void processData() {
try {
int result = 100 / 0;
} catch (ArithmeticException e) {
[Link]("Logged: " + [Link]());
throw new RuntimeException("Data processing failed", e); // re-throw
}
}
public static void main(String[] args) {
try {
processData();
} catch (RuntimeException e) {
[Link]("Caught in main: " + [Link]());
}
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 66


Q91 Write a Java program to create a custom exception hierarchy: AppException -> DatabaseException ->
ConnectionTimeoutException. Throw ConnectionTimeoutException and catch it at the AppException
level.

■ SOLUTION
class AppException extends Exception { AppException(String m) { super(m); } }
class DatabaseException extends AppException { DatabaseException(String m) { super(m); } }
class ConnectionTimeoutException extends DatabaseException { ConnectionTimeoutException(String m){
super(m); } }

public class Main {


static void connectDB() throws ConnectionTimeoutException {
throw new ConnectionTimeoutException("DB connection timed out after 30s");
}
public static void main(String[] args) {
try {
connectDB();
} catch (AppException e) { // catches ConnectionTimeoutException too
[Link]("Caught: [" + [Link]().getSimpleName() + "] " + [Link]());
}
}
}

Q92 Write a Java program to demonstrate that finally executes even when a return statement is present
inside the try block. Print messages from try, finally and after the method call.

■ SOLUTION
public class Main {
static String test() {
try {
[Link]("Inside try");
return "from try";
} finally {
[Link]("Inside finally — always runs!");
}
}
public static void main(String[] args) {
String result = test();
[Link]("Returned: " + result);
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 67


Q93 Write a Java program to create an ATM simulation. Define checked exception
DailyLimitExceededException and unchecked exception InvalidAmountException. Throw appropriate
exceptions during withdraw().

■ SOLUTION
class DailyLimitExceededException extends Exception {
DailyLimitExceededException(String msg) { super(msg); }
}
class InvalidAmountException extends RuntimeException {
InvalidAmountException(String msg) { super(msg); }
}

class ATM {
double balance = 50000; double dailyWithdrawn = 0;
final double DAILY_LIMIT = 20000;
void withdraw(double amount) throws DailyLimitExceededException {
if (amount <= 0) throw new InvalidAmountException("Amount must be positive");
if (amount > balance) throw new InvalidAmountException("Insufficient balance");
if (dailyWithdrawn + amount > DAILY_LIMIT)
throw new DailyLimitExceededException("Daily limit Rs." + DAILY_LIMIT + " exceeded");
balance -= amount; dailyWithdrawn += amount;
[Link]("Withdrawn Rs.%.0f. Remaining: Rs.%.0f%n", amount, balance);
}
}

public class Main {


public static void main(String[] args) {
ATM atm = new ATM();
double[] requests = { 10000, 12000, -500 };
for (double req : requests) {
try { [Link](req); }
catch (DailyLimitExceededException e) { [Link]("Limit: " + [Link]()); }
catch (InvalidAmountException e) { [Link]("Invalid: " + [Link]()); }
}
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 68


Q94 Write a Java program to handle NullPointerException. Create a String variable set to null. Try to call a
method on it. Catch the exception and print an appropriate message.

■ SOLUTION
public class Main {
public static void main(String[] args) {
String str = null;
try {
int len = [Link](); // NullPointerException
[Link]("Length: " + len);
} catch (NullPointerException e) {
[Link]("Error: String is null. Cannot call methods on null.");
} finally {
[Link]("Execution complete.");
}
}
}

Q95 Write a Java program to accept n integers from the user and store them in an array. Handle both
NegativeArraySizeException (if n < 0) and NumberFormatException (if input is not an integer).

■ SOLUTION
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
[Link]("Enter n: ");
int n = [Link]([Link]());
int[] arr = new int[n]; // NegativeArraySizeException if n < 0
for (int i = 0; i < n; i++) {
[Link]("Enter element " + (i+1) + ": ");
arr[i] = [Link]([Link]()); // NumberFormatException if not int
}
[Link]("Array: ");
for (int x : arr) [Link](x + " ");
} catch (NegativeArraySizeException e) {
[Link]("Error: n cannot be negative.");
} catch (NumberFormatException e) {
[Link]("Error: Invalid integer input. " + [Link]());
}
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 69


Q96 Write a Java program to demonstrate a try block with multiple catch blocks followed by a finally block.
Simulate different exceptions based on user input and show which catch block executes.

■ SOLUTION
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("1=ArithmeticException 2=ArrayException 3=NumberFormat other=NoException");
[Link]("Choose: ");
int choice = [Link]();
try {
if (choice == 1) { int x = 1 / 0; }
else if (choice == 2) { int[] a = new int[2]; [Link](a[5]); }
else if (choice == 3) { [Link]("abc"); }
else { [Link]("No exception thrown"); }
} catch (ArithmeticException e) {
[Link]("ArithmeticException caught: " + [Link]());
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBoundsException caught: " + [Link]());
} catch (NumberFormatException e) {
[Link]("NumberFormatException caught: " + [Link]());
} finally {
[Link]("Finally block always executes.");
}
}
}

Unit 6 – Packages 15 Questions

Java OOP Solutions | Vidyalankar Institute of Technology | Page 70


Q97 Write a Java program to create a user-defined package [Link]. Define classes Circle and
Rectangle inside this package with area() methods. Import the package in a Main class and compute
areas.

■ SOLUTION
// File: com/shapes/[Link]
package [Link];
public class Circle {
private double radius;
public Circle(double r) { radius = r; }
public double area() { return [Link] * radius * radius; }
}

// File: com/shapes/[Link]
package [Link];
public class Rectangle {
private double l, w;
public Rectangle(double l, double w) { this.l=l; this.w=w; }
public double area() { return l * w; }
}

// File: [Link]
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
Circle c = new Circle(7);
Rectangle r = new Rectangle(4, 5);
[Link]("Circle area: %.2f%n", [Link]());
[Link]("Rectangle area: %.2f%n", [Link]());
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 71


Q98 Write a Java program to demonstrate subpackages. Create package [Link] with class
HRManager and package [Link] with class PayrollManager. Use both classes in a Main
class.

■ SOLUTION
// File: com/company/hr/[Link]
package [Link];
public class HRManager {
public void hire(String name) { [Link]("HR: Hiring " + name); }
}

// File: com/company/payroll/[Link]
package [Link];
public class PayrollManager {
public void processSalary(String name, double salary) {
[Link]("Payroll: Processed Rs." + salary + " for " + name);
}
}

// File: [Link]
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
HRManager hr = new HRManager();
PayrollManager pm = new PayrollManager();
[Link]("Alice");
[Link]("Alice", 55000);
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 72


Q99 Write a Java program to demonstrate the four access modifiers (public, protected, default, private) with
respect to package access. Create two classes in different packages and test accessibility.

■ SOLUTION
// File: com/demo/[Link]
package [Link];
public class Base {
public int pub = 1; // accessible everywhere
protected int prot = 2; // accessible in same package + subclasses
int def = 3; // package-private: same package only
private int priv = 4; // this class only

public void show() {


[Link]("pub=" + pub + " prot=" + prot +
" def=" + def + " priv=" + priv);
}
}

// File: com/demo/[Link]
package [Link];
public class SamePackage {
public void test() {
Base b = new Base();
[Link]([Link]); // OK
[Link]([Link]); // OK (same package)
[Link]([Link]); // OK (same package)
// [Link] -- NOT accessible
}
}

// File: com/other/[Link]
package [Link];
import [Link];
public class OtherPackage extends Base {
public void test() {
[Link](pub); // OK (public)
[Link](prot); // OK (subclass)
// def -- NOT accessible (different package, not subclass relationship at object level)
// priv -- NOT accessible
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 73


Q10 Write a Java program to demonstrate the use of import static. Import static methods of Java's Math
0 class ([Link], [Link]) using static import and use them without the class name prefix.

■ SOLUTION
import static [Link];
import static [Link];
import static [Link];
import static [Link];

public class Main {


public static void main(String[] args) {
double hypotenuse = sqrt(pow(3, 2) + pow(4, 2));
[Link]("Hypotenuse: " + hypotenuse);
[Link]("PI value: " + PI);
[Link]("Abs(-25): " + abs(-25));
// No Math. prefix needed due to static import
}
}

Q10 Write a Java program to create a package [Link] with classes Account (public) and Transaction
1 (default access). Show that Transaction is not accessible from outside the [Link] package.

■ SOLUTION
// File: com/bank/[Link]
package [Link];
public class Account {
private double balance;
public Account(double balance) { [Link] = balance; }
public double getBalance() { return balance; }
public void deposit(double amount) { balance += amount; }
}

// File: com/bank/[Link] (default/package-private access)


package [Link];
class Transaction { // no 'public' keyword
void record(String type, double amt) {
[Link]("Recorded: " + type + " Rs." + amt);
}
}

// File: [Link]
import [Link];
// import [Link]; // COMPILE ERROR: not visible outside [Link]
public class Main {
public static void main(String[] args) {
Account acc = new Account(10000);
[Link](5000);
[Link]("Balance: " + [Link]());
// Transaction t = new Transaction(); // ERROR
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 74


Q10 Write a Java program to create a utility package [Link] with a class MathHelper containing static
2 methods add(int, int), subtract(int, int) and multiply(int, int). Use MathHelper in a Main class.

■ SOLUTION
// File: com/utils/[Link]
package [Link];
public class MathHelper {
public static int add(int a, int b) { return a + b; }
public static int subtract(int a, int b) { return a - b; }
public static int multiply(int a, int b) { return a * b; }
}

// File: [Link]
import [Link];
public class Main {
public static void main(String[] args) {
[Link]("10 + 3 = " + [Link](10, 3));
[Link]("10 - 3 = " + [Link](10, 3));
[Link]("10 * 3 = " + [Link](10, 3));
}
}

Q10 Write a Java program to show the conflict when two imported packages contain a class with the same
3 name. Import [Link] and [Link] and use a fully qualified name to resolve the conflict.

■ SOLUTION
import [Link];
// import [Link]; // causes conflict — commented out

public class Main {


public static void main(String[] args) {
// Using [Link] normally via import
Date utilDate = new Date();
[Link]("[Link]: " + utilDate);

// Using [Link] via fully qualified name to avoid conflict


[Link] sqlDate = new [Link]([Link]());
[Link]("[Link]: " + sqlDate);
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 75


Q10 Write a Java program to create a mini-project with three packages: [Link] (class Student),
4 [Link] (class StudentService with an enroll() method), and [Link] (Main class). Use all three
together.

■ SOLUTION
// File: com/model/[Link]
package [Link];
public class Student {
public String name; public int rollNo;
public Student(String name, int rollNo) { [Link]=name; [Link]=rollNo; }
public String toString() { return name + " (Roll: " + rollNo + ")"; }
}

// File: com/service/[Link]
package [Link];
import [Link];
public class StudentService {
public void enroll(Student s) {
[Link]("Enrolling student: " + s);
}
}

// File: com/main/[Link]
package [Link];
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
Student s = new Student("Abdulrehman", 101);
new StudentService().enroll(s);
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 76


Q10 Write a Java program to create a package [Link] with class Animal. Create a package [Link]
5 with class Zoo that creates and uses an Animal object from [Link].

■ SOLUTION
// File: com/animals/[Link]
package [Link];
public class Animal {
private String name; private String species;
public Animal(String name, String species) { [Link]=name; [Link]=species; }
public void display() {
[Link]("Animal: " + name + " | Species: " + species);
}
}

// File: com/zoo/[Link]
package [Link];
import [Link];
public class Zoo {
public void addAnimal(String name, String species) {
Animal a = new Animal(name, species);
[Link]("Added to zoo -> ");
[Link]();
}
}

// File: [Link]
import [Link];
public class Main {
public static void main(String[] args) {
Zoo zoo = new Zoo();
[Link]("Simba", "Lion");
[Link]("Nemo", "Clownfish");
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 77


Q10 Write a Java program to demonstrate the wildcard import. Import all classes from [Link] using import
6 [Link].*. Create an ArrayList and a HashMap. Show that subpackages are NOT imported by the
wildcard.

■ SOLUTION
import [Link].*; // imports ArrayList, HashMap, Scanner etc. from [Link]
// [Link].* is NOT imported by the above wildcard
// import [Link]; // needs explicit import

public class Main {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("Java"); [Link]("Python"); [Link]("C++");
[Link]("ArrayList: " + list);

HashMap<String, Integer> map = new HashMap<>();


[Link]("Alice", 95); [Link]("Bob", 87);
[Link]("HashMap: " + map);

// Subpackage NOT imported by [Link].*:


// ConcurrentHashMap chm = new ConcurrentHashMap(); // needs explicit import
[Link]("Note: [Link] is NOT covered by [Link].*");
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 78


Q10 Write a Java program to demonstrate protected access across packages. Create a class Vehicle in
7 package [Link] with a protected method start(). Derive class Car in package [Link] and call
start().

■ SOLUTION
// File: com/vehicles/[Link]
package [Link];
public class Vehicle {
protected void start() {
[Link]("Vehicle engine started");
}
}

// File: com/cars/[Link]
package [Link];
import [Link];
public class Car extends Vehicle {
public void drive() {
start(); // protected method accessible in subclass across packages
[Link]("Car is driving");
}
}

// File: [Link]
import [Link];
public class Main {
public static void main(String[] args) {
Car car = new Car();
[Link]();
// [Link](); // ERROR: protected, not accessible here (different package, not subclass)
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 79


Q10 Write a Java program to create a package [Link] with three classes: Product, Cart and
8 Order. Cart holds a list of Products. Order processes the Cart and displays the bill.

■ SOLUTION
// File: com/ecommerce/[Link]
package [Link];
public class Product {
public String name; public double price;
public Product(String name, double price) { [Link]=name; [Link]=price; }
}

// File: com/ecommerce/[Link]
package [Link];
import [Link];
public class Cart {
ArrayList<Product> items = new ArrayList<>();
public void add(Product p) { [Link](p); [Link]("Added: " + [Link]); }
public double total() {
double sum = 0; for (Product p : items) sum += [Link]; return sum;
}
}

// File: com/ecommerce/[Link]
package [Link];
public class Order {
public void generateBill(Cart cart) {
[Link]("===== BILL =====");
for (Product p : [Link])
[Link]("%-15s Rs.%.2f%n", [Link], [Link]);
[Link]("----------------");
[Link]("TOTAL Rs.%.2f%n", [Link]());
}
}

// File: [Link]
import [Link].*;
public class Main {
public static void main(String[] args) {
Cart cart = new Cart();
[Link](new Product("Laptop", 65000));
[Link](new Product("Mouse", 800));
new Order().generateBill(cart);
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 80


Q10 Write a Java program to show the naming convention for packages. Create a package named
9 [Link] with a class CourseInfo that displays the institute, department and course name.

■ SOLUTION
// File: in/edu/vit/it/[Link]
package [Link];
public class CourseInfo {
private String institute = "Vidyalankar Institute of Technology";
private String department = "Information Technology";
private String courseName = "B.E. Information Technology";
private String batch = "2024-2028";

public void display() {


[Link]("Institute: " + institute);
[Link]("Department: " + department);
[Link]("Course: " + courseName);
[Link]("Batch: " + batch);
}
}

// File: [Link]
import [Link];
public class Main {
public static void main(String[] args) {
new CourseInfo().display();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 81


Q11 Write a Java program to demonstrate that a class with default (package-private) access cannot be
0 used outside its package. Define a default class Helper in [Link]. Try to access it from [Link].

■ SOLUTION
// File: com/tools/[Link]
package [Link];
class Helper { // default (package-private) — no 'public'
void doWork() { [Link]("Helper working"); }
}

// File: com/tools/[Link] (uses Helper within same package — allowed)


package [Link];
public class ToolKit {
public void run() {
Helper h = new Helper(); // OK: same package
[Link]();
}
}

// File: [Link]
import [Link];
// import [Link]; // COMPILE ERROR: Helper is not public
public class Main {
public static void main(String[] args) {
new ToolKit().run(); // indirectly uses Helper via ToolKit
// Helper h = new Helper(); // COMPILE ERROR
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 82


Q11 Write a Java program to create a package [Link] with abstract class Shape and concrete
1 classes Circle and Triangle. Use the package in a driver class that computes area and perimeter.

■ SOLUTION
// File: com/geometry/[Link]
package [Link];
public abstract class Shape {
public abstract double area();
public abstract double perimeter();
public void display() {
[Link]("%s -> Area: %.2f, Perimeter: %.2f%n",
getClass().getSimpleName(), area(), perimeter());
}
}

// File: com/geometry/[Link]
package [Link];
public class Circle extends Shape {
private double r;
public Circle(double r) { this.r = r; }
public double area() { return [Link] * r * r; }
public double perimeter() { return 2 * [Link] * r; }
}

// File: com/geometry/[Link]
package [Link];
public class Triangle extends Shape {
private double a, b, c;
public Triangle(double a, double b, double c) { this.a=a; this.b=b; this.c=c; }
public double area() {
double s = (a+b+c)/2;
return [Link](s*(s-a)*(s-b)*(s-c));
}
public double perimeter() { return a + b + c; }
}

// File: [Link]
import [Link].*;
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(7), new Triangle(3, 4, 5) };
for (Shape s : shapes) [Link]();
}
}

Java OOP Solutions | Vidyalankar Institute of Technology | Page 83

You might also like