Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

OOP Coding Questions v2

The document contains multiple Java programs that demonstrate object-oriented programming concepts by creating various classes such as Person, Dog, Rectangle, Circle, Book, Employee, Bank, TrafficLight, and others. Each program includes constructors, methods for setting and getting attributes, and functionality relevant to the specific class, such as calculating area, managing collections, and updating attributes. The examples illustrate how to implement classes, methods, and basic data handling in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

OOP Coding Questions v2

The document contains multiple Java programs that demonstrate object-oriented programming concepts by creating various classes such as Person, Dog, Rectangle, Circle, Book, Employee, Bank, TrafficLight, and others. Each program includes constructors, methods for setting and getting attributes, and functionality relevant to the specific class, such as calculating area, managing collections, and updating attributes. The examples illustrate how to implement classes, methods, and basic data handling in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

1. Write a Java program to create a class called "Person" with a name and age attribute.

Create two instances of


the "Person" class, set their attributes using the constructor, and print their name and age.

public class Person {


private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to print Person details
public void printDetails() {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Person person1 = new Person("Alice", 25);
Person person2 = new Person("Bob", 30);
person1.printDetails();
person2.printDetails();
}
}

2. Write a Java program to create a class called "Dog" with a name and breed attribute. Create two instances of
the "Dog" class, set their attributes using the constructor and modify the attributes using the setter methods and
print the updated values.

public class Dog {


private String name;
private String breed;

// Constructor
public Dog(String name, String breed) {
this.name = name;
this.breed = breed;
}

// Setter methods
public void setName(String name) {
this.name = name;
}

public void setBreed(String breed) {


this.breed = breed;
}

// Method to print Dog details


public void printDetails() {
System.out.println("Name: " + name + ", Breed: " + breed);
}

public static void main(String[] args) {


Dog dog1 = new Dog("Buddy", "Labrador");
Dog dog2 = new Dog("Max", "Bulldog");

// Updating values using setters


dog1.setName("Charlie");
dog1.setBreed("Golden Retriever");

dog1.printDetails();
dog2.printDetails();
}
}

3. Write a Java program to create a class called "Rectangle" with width and height attributes. Calculate the area
and perimeter of the rectangle.

public class Rectangle {


private double width;
private double height;

// Constructor
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}

// Method to calculate area


public double calculateArea() {
return width * height;
}

// Method to calculate perimeter


public double calculatePerimeter() {
return 2 * (width + height);
}

public static void main(String[] args) {


Rectangle rectangle = new Rectangle(5.0, 10.0);
System.out.println("Area: " + rectangle.calculateArea());
System.out.println("Perimeter: " + rectangle.calculatePerimeter());
}
}

4. Write a Java program to create a class called "Circle" with a radius attribute. You can access and modify this
attribute. Calculate the area and circumference of the circle.

public class Circle {


private double radius;
// Constructor
public Circle(double radius) {
this.radius = radius;
}

// Getter and setter methods


public double getRadius() {
return radius;
}

public void setRadius(double radius) {


this.radius = radius;
}

// Method to calculate area


public double calculateArea() {
return Math.PI * radius * radius;
}

// Method to calculate circumference


public double calculateCircumference() {
return 2 * Math.PI * radius;
}

public static void main(String[] args) {


Circle circle = new Circle(7.0);
System.out.println("Area: " + circle.calculateArea());
System.out.println("Circumference: " + circle.calculateCircumference());
}
}
5. Write a Java program to create a class called "Book" with attributes for title, author, and ISBN, and methods
to add and remove books from a collection.

import java.util.ArrayList;

public class Book {


private String title;
private String author;
private String isbn;

// Constructor
public Book(String title, String author, String isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
}

public String toString() {


return "Title: " + title + ", Author: " + author + ", ISBN: " + isbn;
}

public static void main(String[] args) {


ArrayList<Book> library = new ArrayList<>();

// Adding books
Book book1 = new Book("1984", "George Orwell", "123456789");
Book book2 = new Book("To Kill a Mockingbird", "Harper Lee", "987654321");

library.add(book1);
library.add(book2);

// Removing a book
library.remove(book1);

// Printing remaining books


for (Book book : library) {
System.out.println(book);
}
}
}

6. Write a Java program to create a class called "Employee" with a name, job title, and salary attributes, and
methods to calculate and update salary.

public class Employee {


private String name;
private String jobTitle;
private double salary;
// Constructor
public Employee(String name, String jobTitle, double salary) {
this.name = name;
this.jobTitle = jobTitle;
this.salary = salary;
}
// Method to calculate new salary with a raise
public void updateSalary(double raisePercent) {
salary += salary * (raisePercent / 100);
}
// Method to print Employee details
public void printDetails() {
System.out.println("Name: " + name + ", Job Title: " + jobTitle + ", Salary: " + salary);
}

public static void main(String[] args) {


Employee emp = new Employee("Alice", "Developer", 50000);
emp.updateSalary(10); // Giving a 10% raise
emp.printDetails();
}
}
7. Write a Java program to create a class called "Bank" with a collection of accounts and methods to add and
remove accounts, and to deposit and withdraw money. Also define a class called "Account" to maintain account
details of a particular customer.

import java.util.ArrayList;
class Account {
private String accountNumber;
private String accountHolder;
private double balance;

// Constructor
public Account(String accountNumber, String accountHolder, double balance) {
this.accountNumber = accountNumber;
this.accountHolder = accountHolder;
this.balance = balance;
}

// Methods to deposit and withdraw money


public void deposit(double amount) {
balance += amount;
}

public void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient balance.");
}
}

public double getBalance() {


return balance;
}

public String getAccountHolder() {


return accountHolder;
}

public String getAccountNumber() {


return accountNumber;
}
}

public class Bank {


private ArrayList<Account> accounts = new ArrayList<>();

// Methods to add and remove accounts


public void addAccount(Account account) {
accounts.add(account);
}

public void removeAccount(Account account) {


accounts.remove(account);
}

public void printAccounts() {


for (Account account : accounts) {
System.out.println("Account Holder: " + account.getAccountHolder() + ", Balance: " +
account.getBalance());
}
}

public static void main(String[] args) {


Bank bank = new Bank();
Account acc1 = new Account("001", "John Doe", 1000);
Account acc2 = new Account("002", "Jane Doe", 1500);

bank.addAccount(acc1);
bank.addAccount(acc2);

acc1.deposit(500);
acc2.withdraw(300);
bank.printAccounts();
}
}

8. Write a Java program to create class called "TrafficLight" with attributes for color and duration, and methods
to change the color and check for red or green.

public class TrafficLight {


private String color;
private int duration;

// Constructor
public TrafficLight(String color, int duration) {
this.color = color;
this.duration = duration;
}

// Method to change the color


public void changeColor(String newColor) {
color = newColor;
}

// Method to check if light is red or green


public boolean isRed() {
return color.equalsIgnoreCase("Red");
}

public boolean isGreen() {


return color.equalsIgnoreCase("Green");
}

public void printDetails() {


System.out.println("Color: " + color + ", Duration: " + duration + " seconds");
}

public static void main(String[] args) {


TrafficLight light = new TrafficLight("Red", 60);
light.printDetails();
light.changeColor("Green");
System.out.println("Is green? " + light.isGreen());
}
}

9. Write a Java program to create a class called "Employee" with a name, salary, and hire date attributes, and a
method to calculate years of service.
import java.time.LocalDate;

import java.time.temporal.ChronoUnit;

public class Employee {

private String name;

private double salary;

private LocalDate hireDate;

// Constructor

public Employee(String name, double salary, LocalDate hireDate) {

this.name = name;

this.salary = salary;

this.hireDate = hireDate;

// Method to calculate years of service

public long getYearsOfService() {

return ChronoUnit.YEARS.between(hireDate, LocalDate.now());

public void printDetails() {


System.out.println("Name: " + name + ", Years of Service: " + getYearsOfService());

public static void main(String[] args) {

Employee emp = new Employee("Alice", 50000, LocalDate.of(2015, 5, 10));

emp.printDetails();

10. Write a Java program to create a class called "Student" with a name, grade, and courses attributes, and
methods to add and remove courses.

import java.util.ArrayList;

public class Student {


private String name;
private String grade;
private ArrayList<String> courses;

// Constructor
public Student(String name, String grade) {
this.name = name;
this.grade = grade;
this.courses = new ArrayList<>();
}

// Methods to add and remove courses


public void addCourse(String course) {
courses.add(course);
}

public void removeCourse(String course) {


courses.remove(course);
}
public void printCourses() {
System.out.println("Courses of " + name + ": " + courses);
}

public static void main(String[] args) {


Student student = new Student("Bob", "A");
student.addCourse("Math");
student.addCourse("Science");
student.removeCourse("Math");
student.printCourses();
}
}
11. Write a Java program to create a class called "Library" with a collection of books and methods to add and
remove books.

import java.util.ArrayList;

class Book {
private String title;
private String author;

// Constructor
public Book(String title, String author) {
this.title = title;
this.author = author;
}

public String toString() {


return "Title: " + title + ", Author: " + author;
}
}

public class Library {


private ArrayList<Book> books = new ArrayList<>();

// Methods to add and remove books


public void addBook(Book book) {
books.add(book);
}
public void removeBook(Book book) {
books.remove(book);
}

public void printBooks() {


for (Book book : books) {
System.out.println(book);
}
}

public static void main(String[] args) {


Library library = new Library();
Book book1 = new Book("1984", "George Orwell");
Book book2 = new Book("To Kill a Mockingbird", "Harper Lee");

library.addBook(book1);
library.addBook(book2);
library.printBooks();
}
}
12. Write a Java program to create a class called "Airplane" with a flight number, destination, and departure
time attributes, and methods to check flight status and delay.

import java.time.LocalDateTime;

public class Airplane {


private String flightNumber;
private String destination;
private LocalDateTime departureTime;
private boolean delayed;

// Constructor
public Airplane(String flightNumber, String destination, LocalDateTime departureTime) {
this.flightNumber = flightNumber;
this.destination = destination;
this.departureTime = departureTime;
this.delayed = false;
}

// Methods to check and update flight status


public void delayFlight() {
delayed = true;
}

public boolean isDelayed() {


return delayed;
}

public void printFlightDetails() {


System.out.println("Flight: " + flightNumber + ", Destination: " + destination +
", Departure: " + departureTime + ", Delayed: " + delayed);
}

public static void main(String[] args) {


Airplane flight = new Airplane("AA123", "New York", LocalDateTime.of(2023, 11, 6, 14, 30));
flight.printFlightDetails();
flight.delayFlight();
flight.printFlightDetails();
}
}

13. Write a Java program to create a class called "Inventory" with a collection of products and methods to add
and remove products, and to check for low inventory.

import java.util.ArrayList;

class Product {
private String id;
private String name;
private int quantity;

// Constructor
public Product(String id, String name, int quantity) {
this.id = id;
this.name = name;
this.quantity = quantity;
}

public String getName() {


return name;
}

public int getQuantity() {


return quantity;
}

public void setQuantity(int quantity) {


this.quantity = quantity;
}

@Override
public String toString() {
return "Product: " + name + ", Quantity: " + quantity;
}
}

public class Inventory {


private ArrayList<Product> products = new ArrayList<>();

public void addProduct(Product product) {


products.add(product);
}

public void removeProduct(Product product) {


products.remove(product);
}

public void checkLowInventory() {


for (Product product : products) {
if (product.getQuantity() < 5) {
System.out.println("Low inventory for: " + product.getName());
}
}
}

public static void main(String[] args) {


Inventory inventory = new Inventory();
Product product1 = new Product("001", "Laptop", 10);
Product product2 = new Product("002", "Mouse", 3);

inventory.addProduct(product1);
inventory.addProduct(product2);

inventory.checkLowInventory();
}
}
14. Write a Java program to create a class called "School" with attributes for students, teachers, and classes, and
methods to add and remove students and teachers, and to create classes.

import java.util.ArrayList;

class Student {
private String name;
public Student(String name) { this.name = name; }
public String getName() { return name; }
}

class Teacher {
private String name;
public Teacher(String name) { this.name = name; }
public String getName() { return name; }
}

public class School {


private ArrayList<Student> students = new ArrayList<>();
private ArrayList<Teacher> teachers = new ArrayList<>();

public void addStudent(Student student) {


students.add(student);
}

public void addTeacher(Teacher teacher) {


teachers.add(teacher);
}

public void printSchoolDetails() {


System.out.println("Students: ");
for (Student student : students) {
System.out.println(student.getName());
}
System.out.println("Teachers: ");
for (Teacher teacher : teachers) {
System.out.println(teacher.getName());
}
}

public static void main(String[] args) {


School school = new School();
school.addStudent(new Student("Alice"));
school.addTeacher(new Teacher("Mr. Smith"));
school.printSchoolDetails();
}
}

15. Write a Java program to create a class called "MusicLibrary" with a collection of songs and methods to add
and remove songs, and to play a random song.
import java.util.ArrayList;
import java.util.Random;

class Song {
private String title;
public Song(String title) { this.title = title; }
public String getTitle() { return title; }
}

public class MusicLibrary {


private ArrayList<Song> songs = new ArrayList<>();

public void addSong(Song song) {


songs.add(song);
}

public void playRandomSong() {


if (!songs.isEmpty()) {
Random random = new Random();
Song song = songs.get(random.nextInt(songs.size()));
System.out.println("Playing: " + song.getTitle());
} else {
System.out.println("No songs in the library.");
}
}

public static void main(String[] args) {


MusicLibrary library = new MusicLibrary();
library.addSong(new Song("Song A"));
library.addSong(new Song("Song B"));
library.playRandomSong(); } }
16. Write a Java program to create a class called "Shape" with abstract methods for calculating area and
perimeter, and subclasses for "Rectangle", "Circle", and "Triangle".

abstract class Shape {


public abstract double calculateArea();
public abstract double calculatePerimeter();
}

class Rectangle extends Shape {


private double width, height;

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

public double calculateArea() {


return width * height;
}

public double calculatePerimeter() {


return 2 * (width + height);
}
}

class Circle extends Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

public double calculateArea() {


return Math.PI * radius * radius;
}

public double calculatePerimeter() {


return 2 * Math.PI * radius;
}
}

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 calculateArea() {


double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}

public double calculatePerimeter() {


return a + b + c;
}
}

public class Main {


public static void main(String[] args) {
Shape rect = new Rectangle(5, 7);
Shape circle = new Circle(3);
Shape triangle = new Triangle(3, 4, 5);

System.out.println("Rectangle Area: " + rect.calculateArea());


System.out.println("Circle Area: " + circle.calculateArea());
System.out.println("Triangle Area: " + triangle.calculateArea());
}
}
17. Write a Java program to create a class called "Movie" with attributes for title, director, actors, and reviews,
and methods for adding and retrieving reviews.

import java.util.ArrayList;

class Movie {
private String title;
private String director;
private ArrayList<String> reviews = new ArrayList<>();

public Movie(String title, String director) {


this.title = title;
this.director = director;
}

public void addReview(String review) {


reviews.add(review);
}

public void printReviews() {


System.out.println("Reviews for " + title + ": " + reviews);
}

public static void main(String[] args) {


Movie movie = new Movie("Inception", "Christopher Nolan");
movie.addReview("Amazing movie!");
movie.addReview("A mind-bending experience.");
movie.printReviews();
}
}
18. Write a Java program to create a class called "Restaurant" with attributes for menu items, prices, and
ratings, and methods to add and remove items, and to calculate average rating.

import java.util.HashMap;

public class Restaurant {


private HashMap<String, Double> menu = new HashMap<>();
private HashMap<String, Double> ratings = new HashMap<>();

public void addMenuItem(String item, double price) {


menu.put(item, price);
}

public void removeMenuItem(String item) {


menu.remove(item);
}

public void addRating(String item, double rating) {


ratings.put(item, rating);
}

public double calculateAverageRating() {


double total = 0;
for (double rating : ratings.values()) {
total += rating;
}
return ratings.size() > 0 ? total / ratings.size() : 0;
}

public void printMenu() {


System.out.println("Menu: " + menu);
System.out.println("Average Rating: " + calculateAverageRating());
}

public static void main(String[] args) {


Restaurant res = new Restaurant();
res.addMenuItem("Pizza", 8.99);
res.addMenuItem("Burger", 5.99);
res.addRating("Pizza", 4.5);
res.addRating("Burger", 4.0);
res.printMenu();
}
}
19. Write a Java program to create a class with methods to search for flights and hotels, and to book and cancel
reservations.

import java.util.ArrayList;

class ReservationSystem {
private ArrayList<String> flights = new ArrayList<>();
private ArrayList<String> hotels = new ArrayList<>();

public void addFlight(String flight) {


flights.add(flight);
}

public void cancelFlight(String flight) {


flights.remove(flight);
}

public void addHotel(String hotel) {


hotels.add(hotel);
}

public void cancelHotel(String hotel) {


hotels.remove(hotel);
}

public void printReservations() {


System.out.println("Flights: " + flights);
System.out.println("Hotels: " + hotels);
}

public static void main(String[] args) {


ReservationSystem system = new ReservationSystem();
system.addFlight("AA123");
system.addHotel("Hilton");
system.printReservations();
}
}

20. Write a Java program to create a class called "BankAccount" with attributes for account number, account
holder's name, and balance. Include methods for depositing and withdrawing money, as well as checking the
balance. Create a subclass called "SavingsAccount" that adds an interest rate attribute and a method to apply
interest.
class BankAccount {
private String accountNumber;
private String holderName;
private double balance;

public BankAccount(String accountNumber, String holderName, double balance) {


this.accountNumber = accountNumber;
this.holderName = holderName;
this.balance = balance;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) {


if (balance >= amount) {
balance -= amount;
} else {
System.out.println("Insufficient balance.");
}
}

public double getBalance() {


return balance;
}
}

class SavingsAccount extends BankAccount {


private double interestRate;

public SavingsAccount(String accountNumber, String holderName, double balance, double interestRate) {


super(accountNumber, holderName, balance);
this.interestRate = interestRate;
}

public void applyInterest() {


deposit(getBalance() * interestRate / 100);
}

public static void main(String[] args) {


SavingsAccount account = new SavingsAccount("001", "John Doe", 1000, 5);
account.applyInterest();
System.out.println("Balance after interest: " + account.getBalance());
}
}
21. Write a Java program to create a class called "Vehicle" with attributes for make, model, and year. Create
subclasses "Car" and "Truck" that add specific attributes like trunk size for cars and payload capacity for trucks.
Implement a method to display vehicle details in each subclass.

class Vehicle {
private String make;
private String model;
private int year;

public Vehicle(String make, String model, int year) {


this.make = make;
this.model = model;
this.year = year;
}

public void printDetails() {


System.out.println("Make: " + make + ", Model: " + model + ", Year: " + year);
}
}

class Car extends Vehicle {


private double trunkSize;

public Car(String make, String model, int year, double trunkSize) {


super(make, model, year);
this.trunkSize = trunkSize;
}

@Override
public void printDetails() {
super.printDetails();
System.out.println("Trunk Size: " + trunkSize + " cu ft");
}
}

class Truck extends Vehicle {


private double payloadCapacity;

public Truck(String make, String model, int year, double payloadCapacity) {


super(make, model, year);
this.payloadCapacity = payloadCapacity;
}

@Override
public void printDetails() {
super.printDetails();
System.out.println("Payload Capacity: " + payloadCapacity + " kg");
}

public static void main(String[] args) {


Car car = new Car("Toyota", "Camry", 2020, 15.1);
Truck truck = new Truck("Ford", "F-150", 2019, 1320);

car.printDetails();
truck.printDetails();
}
}

22. Write a Java program to create a class called "Customer" with attributes for name, email, and purchase
history. Implement methods to add purchases to the history and calculate total expenditure. Create a subclass
"LoyalCustomer" that adds a discount rate attribute and a method to apply the discount.

import java.util.ArrayList;

class Customer {
private String name;
private String email;
private ArrayList<Double> purchaseHistory = new ArrayList<>();

public Customer(String name, String email) {


this.name = name;
this.email = email;
}

public void addPurchase(double amount) {


purchaseHistory.add(amount);
}

public double calculateTotalExpenditure() {


double total = 0;
for (double amount : purchaseHistory) {
total += amount;
}
return total;
}
}

class LoyalCustomer extends Customer {


private double discountRate;

public LoyalCustomer(String name, String email, double discountRate) {


super(name, email);
this.discountRate = discountRate;
}

public double applyDiscount(double amount) {


return amount - (amount * discountRate / 100);
}

public static void main(String[] args) {


LoyalCustomer customer = new LoyalCustomer("Alice", "alice@example.com", 10);
double discountedAmount = customer.applyDiscount(100);
System.out.println("Discounted Amount: " + discountedAmount);
}
}

23. Write a Java program to create a class called "Course" with attributes for course name, instructor, and
credits. Create a subclass "OnlineCourse" that adds attributes for platform and duration. Implement methods to
display course details and check if the course is eligible for a certificate based on duration.

class Course {
private String courseName;
private String instructor;
private int credits;

public Course(String courseName, String instructor, int credits) {


this.courseName = courseName;
this.instructor = instructor;
this.credits = credits;
}

public void displayCourseDetails() {


System.out.println("Course: " + courseName + ", Instructor: " + instructor + ", Credits: " + credits);
}
}

class OnlineCourse extends Course {


private String platform;
private int duration;

public OnlineCourse(String courseName, String instructor, int credits, String platform, int duration) {
super(courseName, instructor, credits);
this.platform = platform;
this.duration = duration;
}

public boolean isEligibleForCertificate() {


return duration >= 10; // Example: courses over 10 hours are eligible
}

@Override
public void displayCourseDetails() {
super.displayCourseDetails();
System.out.println("Platform: " + platform + ", Duration: " + duration + " hours");
}

public static void main(String[] args) {


OnlineCourse course = new OnlineCourse("Java Programming", "Dr. Smith", 3, "Udemy", 12);
course.displayCourseDetails();
System.out.println("Eligible for Certificate: " + course.isEligibleForCertificate());
}
}
24. Write a Java program to create a class called "ElectronicsProduct" with attributes for product ID, name, and
price. Implement methods to apply a discount and calculate the final price. Create a subclass "
WashingMachine" that adds a warranty period attribute and a method to extend the warranty.

class ElectronicsProduct {
private String productID;
private String name;
private double price;

public ElectronicsProduct(String productID, String name, double price) {


this.productID = productID;
this.name = name;
this.price = price;
}

public double applyDiscount(double discountPercentage) {


return price - (price * discountPercentage / 100);
}
}

class WashingMachine extends ElectronicsProduct {


private int warrantyPeriod;

public WashingMachine(String productID, String name, double price, int warrantyPeriod) {


super(productID, name, price);
this.warrantyPeriod = warrantyPeriod;
}

public void extendWarranty(int additionalYears) {


warrantyPeriod += additionalYears;
}

public static void main(String[] args) {


WashingMachine wm = new WashingMachine("WM001", "LG Washing Machine", 500.0, 2);
System.out.println("Price after 10% discount: " + wm.applyDiscount(10));
wm.extendWarranty(1);
System.out.println("New warranty period: " + wm.warrantyPeriod + " years");
}
}

25. Write a Java program to create a class called "Building" with attributes for address, number of floors, and
total area. Create subclasses "ResidentialBuilding" and "CommercialBuilding" that add specific attributes like
number of apartments for residential and office space for commercial buildings. Implement a method to
calculate the total rent for each subclass.

class Building {
private String address;
private int numberOfFloors;
private double totalArea;

public Building(String address, int numberOfFloors, double totalArea) {


this.address = address;
this.numberOfFloors = numberOfFloors;
this.totalArea = totalArea;
}
}

class ResidentialBuilding extends Building {


private int numberOfApartments;

public ResidentialBuilding(String address, int numberOfFloors, double totalArea, int numberOfApartments)


{
super(address, numberOfFloors, totalArea);
this.numberOfApartments = numberOfApartments;
}

public double calculateTotalRent(double rentPerApartment) {


return numberOfApartments * rentPerApartment;
}
}

class CommercialBuilding extends Building {


private double officeSpace;

public CommercialBuilding(String address, int numberOfFloors, double totalArea, double officeSpace) {


super(address, numberOfFloors, totalArea);
this.officeSpace = officeSpace;
}

public double calculateTotalRent(double rentPerSqFt) {


return officeSpace * rentPerSqFt;
}
public static void main(String[] args) {
ResidentialBuilding rb = new ResidentialBuilding("123 Street", 5, 10000, 20);
System.out.println("Total Rent for Residential Building: " + rb.calculateTotalRent(500));

CommercialBuilding cb = new CommercialBuilding("456 Avenue", 10, 20000, 15000);


System.out.println("Total Rent for Commercial Building: " + cb.calculateTotalRent(20));
}
}

26. Write a Java program to create a class called "Event" with attributes for event name, date, and location.
Create subclasses "Seminar" and "MusicalPerformance" that add specific attributes like number of speakers for
seminars and performer list for concerts. Implement methods to display event details and check for conflicts in
the event schedule.

class Building {
private String address;
private int numberOfFloors;
private double totalArea;

public Building(String address, int numberOfFloors, double totalArea) {


this.address = address;
this.numberOfFloors = numberOfFloors;
this.totalArea = totalArea;
}
}

class ResidentialBuilding extends Building {


private int numberOfApartments;

public ResidentialBuilding(String address, int numberOfFloors, double totalArea, int numberOfApartments)


{
super(address, numberOfFloors, totalArea);
this.numberOfApartments = numberOfApartments;
}

public double calculateTotalRent(double rentPerApartment) {


return numberOfApartments * rentPerApartment;
}
}

class CommercialBuilding extends Building {


private double officeSpace;

public CommercialBuilding(String address, int numberOfFloors, double totalArea, double officeSpace) {


super(address, numberOfFloors, totalArea);
this.officeSpace = officeSpace;
}

public double calculateTotalRent(double rentPerSqFt) {


return officeSpace * rentPerSqFt;
}

public static void main(String[] args) {


ResidentialBuilding rb = new ResidentialBuilding("123 Street", 5, 10000, 20);
System.out.println("Total Rent for Residential Building: " + rb.calculateTotalRent(500));

CommercialBuilding cb = new CommercialBuilding("456 Avenue", 10, 20000, 15000);


System.out.println("Total Rent for Commercial Building: " + cb.calculateTotalRent(20));
}
}
27. Write a Java program to create a class called "CustomerOrder" with attributes for order ID, customer, and
order date. Create a subclass "OnlineOrder" that adds attributes for delivery address and tracking number.
Implement methods to calculate delivery time based on the address and update the tracking status.

class CustomerOrder {
private String orderId;
private String customer;
private String orderDate;

public CustomerOrder(String orderId, String customer, String orderDate) {


this.orderId = orderId;
this.customer = customer;
this.orderDate = orderDate;
}
}

class OnlineOrder extends CustomerOrder {


private String deliveryAddress;
private String trackingNumber;

public OnlineOrder(String orderId, String customer, String orderDate, String deliveryAddress, String
trackingNumber) {
super(orderId, customer, orderDate);
this.deliveryAddress = deliveryAddress;
this.trackingNumber = trackingNumber;
}

public void updateTrackingStatus(String status) {


System.out.println("Tracking " + trackingNumber + ": " + status);
}

public static void main(String[] args) {


OnlineOrder order = new OnlineOrder("001", "John", "2024-11-01", "123 Elm St", "TRK123");
order.updateTrackingStatus("In Transit");
}
}
28. Write a Java program to create a class called "Reservation" with attributes for reservation ID, customer
name, and date. Create subclasses "ResortReservation" and "RailwayReservation" that add specific attributes
like room number for hotels and seat number for flights. Implement methods to check reservation status and
modify reservation details.

class Reservation {
private String reservationId;
private String customerName;
private String date;

public Reservation(String reservationId, String customerName, String date) {


this.reservationId = reservationId;
this.customerName = customerName;
this.date = date;
}
}

class ResortReservation extends Reservation {


private int roomNumber;

public ResortReservation(String reservationId, String customerName, String date, int roomNumber) {


super(reservationId, customerName, date);
this.roomNumber = roomNumber;
}

public void modifyRoom(int newRoomNumber) {


this.roomNumber = newRoomNumber;
System.out.println("Room updated to: " + newRoomNumber);
}
}

class RailwayReservation extends Reservation {


private int seatNumber;

public RailwayReservation(String reservationId, String customerName, String date, int seatNumber) {


super(reservationId, customerName, date);
this.seatNumber = seatNumber;
}

public void modifySeat(int newSeatNumber) {


this.seatNumber = newSeatNumber;
System.out.println("Seat updated to: " + newSeatNumber);
}

public static void main(String[] args) {


ResortReservation resortReservation = new ResortReservation("R001", "Alice", "2024-12-01", 101);
resortReservation.modifyRoom(102);

RailwayReservation railwayReservation = new RailwayReservation("RR001", "Bob", "2024-12-02", 12);


railwayReservation.modifySeat(15);
}
}
29. Write a Java program to create a class called "Pet" with attributes for name, species, and age. Create
subclasses "Dog" and "Bird" that add specific attributes like favorite toy for dogs and wing span for birds.
Implement methods to display pet details and calculate the pet's age in human years.

class Pet {
private String name;
private String species;
private int age;

public Pet(String name, String species, int age) {


this.name = name;
this.species = species;
this.age = age;
}
}

class Dog extends Pet {


private String favoriteToy;

public Dog(String name, int age, String favoriteToy) {


super(name, "Dog", age);
this.favoriteToy = favoriteToy;
}
}

class Bird extends Pet {


private double wingSpan;

public Bird(String name, int age, double wingSpan) {


super(name, "Bird", age);
this.wingSpan = wingSpan;
}

public static void main(String[] args) {


Dog dog = new Dog("Buddy", 4, "Ball");
Bird bird = new Bird("Tweety", 2, 0.5);
}
}
30. Write a Java program to create a class called "GymMembership" with attributes for member name,
membership type, and duration. Create a subclass "PremiumMembership" that adds attributes for personal
trainer availability and spa access. Implement methods to calculate membership fees and check for special
offers based on membership type.

class Book {
private String title;
private String author;
private double price;

public Book(String title, String author, double price) {


this.title = title;
this.author = author;
this.price = price;
}

public void displayDetails() {


System.out.println("Title: " + title + ", Author: " + author + ", Price: $" + price);
}
}

class Fiction extends Book {


private String genre;

public Fiction(String title, String author, double price, String genre) {


super(title, author, price);
this.genre = genre;
}

@Override
public void displayDetails() {
super.displayDetails();
System.out.println("Genre: " + genre);
}
}

class NonFiction extends Book {


private String field;

public NonFiction(String title, String author, double price, String field) {


super(title, author, price);
this.field = field;
}

@Override
public void displayDetails() {
super.displayDetails();
System.out.println("Field: " + field);
}

public static void main(String[] args) {


Fiction fiction = new Fiction("Harry Potter", "J.K. Rowling", 29.99, "Fantasy");
NonFiction nonFiction = new NonFiction("Sapiens", "Yuval Noah Harari", 19.99, "History");

fiction.displayDetails();
nonFiction.displayDetails();
}
}

You might also like