Assignment
Assignment
}
}
OUTPUT:
3. Vehicle Hierarchy
Scenario: Design a base class “Vehicle” with a method “move()”. Derive classes “Car” and “Bike” that override
the “move()” method to define how each vehicle moves.
PROGRAM:
class vehicle{
void move(){
System.out.println("move");
}
}
PROGRAM:
class product {
void getprice(){
System.out.println("getprice");
}
}
class electronics extends product{
@Override
void getprice(){
System.out.println("20% discount for electronics");
}
}
class clothing extends product{
@Override
void getprice(){
System.out.println("25% discount for clothing");
}
}
class grocery extends product{
@Override
void getprice(){
System.out.println("30% discount for grocery");
}
}
public class producti{
public static void main(String[] args) {
electronics e =new electronics();
e.getprice();
clothing c= new clothing();
c.getprice();
grocery g= new grocery();
g.getprice();
}
}
OUTPUT:
8. Student Grading System
Scenario: Create a base class “Student” with attributes like “name and marks”. Derive classes “Undergraduate
and Postgraduate” that override a method “calculateGrade()” based on different grading criteria.
PROGRAM:
class Student {
protected String name;
protected int marks;
public Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
public void calculateGrade() {
System.out.println("Grade calculation not defined.");
}
}
class Undergraduate extends Student {
public Undergraduate(String name, int marks) {
super(name, marks);
}
@Override
public void calculateGrade() {
System.out.println(name + "'s Grade: " + (marks >= 50 ? "Pass" : "Fail"));
}
}
class Postgraduate extends Student {
public Postgraduate(String name, int marks) {
super(name, marks);
}
@Override
public void calculateGrade() {
System.out.println(name + "'s Grade: " + (marks >= 60 ? "Pass" : "Fail"));
}
}
public class StudentGrading {
public static void main(String[] args) {
Student ug = new Undergraduate("lakshmi", 55);
ug.calculateGrade();
Student pg = new Postgraduate("praba", 55);
pg.calculateGrade();
}
}
OUTPUT:
OUTPUT:
OUTPUT:
ASSIGNMENT-4
1.Scenario: A company wants to create a system to manage its employees' daily activities. The system
needsdifferent types of employees like managers and developers, each with specific responsibilities.
Question:
Write an abstract class Employee with a method work(). Create two concrete classes, Manager and Developer,
that extend Employee. Implement the work() method differently for each class.
PROGRAM:
abstract class employee{
abstract void works();
}
class managers extends employee{
protected void works(){
System.out.println("Manage the work");
}
}
class developers extends employee{
void works(){
System.out.println("Develope the tool");
}
}
class employeeabstract{
public static void main(String[] args) {
managers ma=new managers();
ma.works();
developers de=new developers();
de.works();
}
}
OUTPUT:
2. Scenario: You are designing an application for a university where multiple departments like Science, Arts, and
Commerce need to implement a common method to calculate department budgets.
Question:
Create an abstract class Department with an abstract method calculateBudget(). Implement it in
ScienceDepartment, ArtsDepartment, and CommerceDepartment classes with different logic.
PROGRAM:
abstract class Department {
String departmentName;
public Department(String departmentName) {
this.departmentName = departmentName;
}
public abstract double calculateBudget();
}
class ScienceDepartment extends Department {
double labExpenses;
double facultySalaries;
public ScienceDepartment(String departmentName, double labExpenses, double facultySalaries) {
super(departmentName);
this.labExpenses = labExpenses;
this.facultySalaries = facultySalaries;
}
@Override
public double calculateBudget() {
return labExpenses + facultySalaries + 50000;
}
}
class ArtsDepartment extends Department {
double artMaterialsCost;
double facultySalaries;
public ArtsDepartment(String departmentName, double artMaterialsCost, double facultySalaries) {
super(departmentName);
this.artMaterialsCost = artMaterialsCost;
this.facultySalaries = facultySalaries;
}
@Override
public double calculateBudget() {
return artMaterialsCost + facultySalaries + 30000;
}
}
class CommerceDepartment extends Department {
double infrastructureCost;
double facultySalaries;
public CommerceDepartment(String departmentName, double infrastructureCost, double facultySalaries) {
super(departmentName);
this.infrastructureCost = infrastructureCost;
this.facultySalaries = facultySalaries;
}
@Override
public double calculateBudget() {
return infrastructureCost + facultySalaries + 40000;
}
}
public class budgetabs {
public static void main(String[] args) {
Department science = new ScienceDepartment("Science Department", 20000, 50000);
Department arts = new ArtsDepartment("Arts Department", 10000, 40000);
Department commerce = new CommerceDepartment("Commerce Department", 15000, 45000);
System.out.println(science.departmentName + " Budget: " + science.calculateBudget());
System.out.println(arts.departmentName + " Budget: " + arts.calculateBudget());
System.out.println(commerce.departmentName + " Budget: " + commerce.calculateBudget());
}
}
OUTPUT:
3. Scenario: A vehicle manufacturing company wants to create a base class for all vehicles and provide specific
features for different types of vehicles like cars, bikes, and trucks.
Question:
Define an abstract class Vehicle with methods start() and stop(). Implement these methods in Car, Bike, and
Truck classes with unique messages.
PROGRAM:
abstract class Vehicle {
public abstract void start();
public abstract void stop();
}
class Car extends Vehicle {
@Override
public void start() {
System.out.println("The car is starting!");
}
@Override
public void stop() {
System.out.println("The car is stopping!");
}
}
class Bike extends Vehicle {
@Override
public void start() {
System.out.println("The bike is starting!");
}
@Override
public void stop() {
System.out.println("The bike is stopping!");
}
}
class Truck extends Vehicle {
@Override
public void start() {
System.out.println("The truck is starting!");
}
@Override
public void stop() {
System.out.println("The truck is stopping!");
}
}
public class vehicleabs{
public static void main(String[] args) {
Vehicle car = new Car();
Vehicle bike = new Bike();
Vehicle truck = new Truck();
car.start();
car.stop();
bike.start();
bike.stop();
truck.start();
truck.stop();
}
}
OUTPUT:
4. Scenario: A payment gateway needs to handle different payment modes like credit card, debit card, and UPI.
Each mode has a unique way to process the payment.
Question:
Create an abstract class Payment with an abstract method processPayment(). Implement this method in
CreditCardPayment, DebitCardPayment, and UPIPayment classes.
PROGRAM:
abstract class Payment {
abstract void processPayment();}
class CreditCardPayment extends Payment {
public void processPayment() {
System.out.println("Processing payment through Credit Card..."); }}
class DebitCardPayment extends Payment {
public void processPayment() {
System.out.println("Processing payment through Debit Card...");}}
class UPIPayment extends Payment {
public void processPayment() {
System.out.println("Processing payment through UPI...");}}
public class paymentabs{
public static void main(String[] args) {
Payment cc = new CreditCardPayment();
Payment db = new DebitCardPayment();
Payment upi = new UPIPayment();
cc.processPayment();
db.processPayment();
upi.processPayment();
}
}
OUTPUT:
5. Scenario: A company needs to implement a library management system where different types of members
like students, faculty, and external members can borrow books.
Question:
Write an abstract class LibraryMember with a method borrowBook(). Extend it to StudentMember,
FacultyMember, and ExternalMember classes with specific borrowing logic.
PROGRAM:
abstract class LibraryMember {
protected String name;
public LibraryMember(String name) {
this.name = name;}
public abstract void borrowBook(String bookTitle);}
class StudentMember extends LibraryMember {
public StudentMember(String name) {
super(name);}
@Override
public void borrowBook(String bookTitle) {
System.out.println(name + " (Student) borrowed the book: " + bookTitle);}}
class FacultyMember extends LibraryMember {
public FacultyMember(String name) {
super(name);}
@Override
public void borrowBook(String bookTitle) {
System.out.println(name + " (Faculty) borrowed the book: " + bookTitle);
}
}
class ExternalMember extends LibraryMember {
public ExternalMember(String name) {
super(name);}
public void borrowBook(String bookTitle) {
System.out.println(name + " (External Member) borrowed the book: " + bookTitle);
}
}
public class libraryabs {
public static void main(String[] args) {
LibraryMember student = new StudentMember("xxx");
LibraryMember faculty = new FacultyMember("yyy");
LibraryMember external = new ExternalMember("zzz");
student.borrowBook("Java ");
faculty.borrowBook("python");
external.borrowBook("c");
}
}
OUTPUT:
6. Scenario: A banking system requires secure handling of customer details like account number, balance, and
account type, allowing only controlled access to these fields.
Question:
Write a class BankAccount that encapsulates accountNumber, balance, and accountType fields. Use getter and
setter methods to manage access to these fields.
PROGRAM:
class BankAccounts {
private String accountNumber;
private double balance;
private String accountType;
public BankAccounts(String accountNumber, double balance, String accountType) {
this.accountNumber = accountNumber;
this.balance = balance;
this.accountType = accountType;
}
public String getAccountNumber() {
return accountNumber;}
public double getBalance() {
return balance;}
public void setBalance(double balance) {
if (balance >= 0) {
this.balance = balance;
} else {
System.out.println("Balance cannot be negative.");
}
}
public String getAccountType() {
return accountType;}
public void setAccountType(String accountType) {
if (accountType.equals("Checking") || accountType.equals("Savings")) {
this.accountType = accountType;
} else {
System.out.println("Invalid account type. Only Checking or Savings allowed.");
}
}
}
public class bankaccabs {
public static void main(String[] args) {
BankAccounts account = new BankAccounts("12345678", 1000.0, "Checking");
System.out.println("Account Number: " + account.getAccountNumber());
System.out.println("Balance: Rs" + account.getBalance());
System.out.println("Account Type: " + account.getAccountType());
account.setBalance(1500.0);
account.setAccountType("Savings");
System.out.println("\nAfter update:");
System.out.println("Balance: Rs" + account.getBalance());
System.out.println("Account Type: " + account.getAccountType());
}
}
OUTPUT:
7. Scenario: An e-commerce platform needs to manage product details like product ID, name, and price. Only
the price of a product can be updated after the product is added.
Question:
Create a class Product that encapsulates productId, name, and price. Implement getter methods for all fields
and a setter method for price.
PROGRAM:
class Products {
private String productId;
private String name;
private double price;
public Products(String productId, String name, double price) {
this.productId = productId;
this.name = name;
this.price = price;
}
public String getProductId() {
return productId;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if (price >= 0) {
this.price = price;
} else {
System.out.println("Price cannot be negative.");
}
}
}
public class productabs {
public static void main(String[] args) {
Products product = new Products("P123", "Laptop", 30000);
System.out.println("Product ID: " + product.getProductId());
System.out.println("Product Name: " + product.getName());
System.out.println("Product Price: Rs" + product.getPrice());
product.setPrice(10000);
System.out.println("\nAfter price update:");
System.out.println("Product Price: Rs" + product.getPrice());
product.setPrice(-500.00);
}
}
OUTPUT:
8. Scenario: A hospital management system requires maintaining patient information like name, age, and
medical history. The medical history should only be accessible for reading.
Question:
Write a class Patient that encapsulates the name, age, and medicalHistory fields. Implement getter and setter
methods as required.
PROGRAM:
class Patient {
private String name;
private int age;
private String medicalHistory;
public Patient(String name, int age, String medicalHistory) {
this.name = name;
this.age = age;
this.medicalHistory = medicalHistory;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getMedicalHistory() {
return medicalHistory;
}
}
public class medicalabs {
public static void main(String[] args) {
Patient patient = new Patient("xxx", 45, "Diabetes, High Blood Pressure");
System.out.println("Patient Name: " + patient.getName());
System.out.println("Patient Age: " + patient.getAge());
System.out.println("Medical History: " + patient.getMedicalHistory());
patient.setName("yyy");
patient.setAge(46);
System.out.println("\nAfter updates:");
System.out.println("Patient Name: " + patient.getName());
System.out.println("Patient Age: " + patient.getAge());
}
}
OUTPUT:
9. Scenario: A car rental service needs to store car details like car model, registration number, and rental price.
These details should only be accessible through proper methods.
Question:
Write a class Car with encapsulated fields model, registrationNumber, and rentalPrice. Provide controlled
access using getter and setter methods.
PROGRAM:
class Cars {
private String model;
private String registrationNumber;
private double rentalPrice;
OUTPUT:
10. Scenario: A student portal requires managing student information like roll number, name, and grades. The
grades can be updated only after verifying certain conditions.
Question:
Create a class Student that encapsulates rollNumber, name, and grades. Implement appropriate getter and
setter methods with validation logic in the setter for grades.
PROGRAM:
class Students {
private int rollNumber;
private String name;
private double grades;
public Students(int rollNumber, String name, double grades) {
this.rollNumber = rollNumber;
this.name = name;
setGrades(grades);
}
public int getRollNumber() {
return rollNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getGrades() {
return grades;
}
public void setGrades(double grades) {
if (grades >= 0 && grades <= 100) {
this.grades = grades;
} else {
System.out.println("Invalid grade! Must be between 0 and 100.");
}
}
public void displayStudentInfo() {
System.out.println("\nRoll Number: " + rollNumber);
System.out.println("Name: " + name);
System.out.println("Grades: " + grades);
}
}
public class studentabs{
public static void main(String[] args) {
Students student = new Students(101, "John Doe", 85);
student.displayStudentInfo();
student.setGrades(110);
student.setGrades(92);
student.displayStudentInfo();
}
}
OUTPUT:
ASSIGNMENT-5
}
}
OUTPUT:
2. Inheritance
Scenario: Build a system for a wildlife sanctuary. Create a base class Animal with attributes species and age.
Extend it into subclasses Bird and Mammal, each with unique attributes like wingSpan for birds and furType for
mammals. Write a program to create and display details of various animals.
PROGRAM:
class Animal {
protected String species;
protected int age;
public Animal(String species, int age) {
this.species = species;
this.age = age;
}
public void displayAnimalDetails() {
System.out.println("Species: " + species);
System.out.println("Age: " + age + " years");
}
}
class Bird extends Animal {
private double wingSpan;
public Bird(String species, int age, double wingSpan) {
super(species, age);
this.wingSpan = wingSpan;
}
public void displayBirdDetails() {
displayAnimalDetails();
System.out.println("Wing Span: " + wingSpan + " meters");
}
}
class Mammal extends Animal {
private String furType;
public Mammal(String species, int age, String furType) {
super(species, age);
this.furType = furType;
}
public void displayMammalDetails() {
displayAnimalDetails();
System.out.println("Fur Type: " + furType);
}
}
public class animals {
public static void main(String[] args) {
Animal tiger = new Mammal("Tiger", 5, "Striped");
Animal eagle = new Bird("Eagle", 3, 2.5);
System.out.println("Tiger Details:");
((Mammal) tiger).displayMammalDetails();
System.out.println("\nEagle Details:");
((Bird) eagle).displayBirdDetails();
}
}
OUTPUT:
3. Polymorphism
Scenario: Create a gaming application where players can use different weapons. Define a base class Weapon
with a method use(). Create subclasses Sword, Gun, and Bow, overriding the use() method to show weapon-
specific messages. Demonstrate polymorphism by invoking the methods dynamically.
PROGRAM:
class Weapon {
public void use() {
System.out.println("Using a weapon...");
}
}
class Sword extends Weapon {
public void use() {
System.out.println("Swinging the sword!");
}
}
class Gun extends Weapon {
public void use() {
System.out.println("Firing the gun!");
}
}
class Bow extends Weapon {
public void use() {
System.out.println("Shooting the arrow with the bow!");
}
}
public class weapons {
public static void main(String[] args) {
Weapon sword = new Sword();
Weapon gun = new Gun();
Weapon bow = new Bow();
sword.use();
gun.use();
bow.use();
}
}
OUTPUT:
4. Encapsulation
Scenario: Implement a HealthTracker class to monitor steps taken by a user. Use private attributes userId,
stepsTaken, and caloriesBurned. Ensure only valid step counts can be updated using a setter method and
calculate calories automatically based on the steps taken.
PROGRAM:
class HealthTracker {
private String userId;
private int stepsTaken;
private double caloriesBurned;
public HealthTracker(String userId) {
this.userId = userId;
this.stepsTaken = 0;
this.caloriesBurned = 0.0;
}
public String getUserId() {
return userId;
}
public int getStepsTaken() {
return stepsTaken;
}
public double getCaloriesBurned() {
return caloriesBurned;
}
public void setStepsTaken(int steps) {
if (steps >= 0) {
this.stepsTaken = steps;
this.caloriesBurned = calculateCalories(steps);
} else {
System.out.println("Error: Steps taken cannot be negative.");
}
}
private double calculateCalories(int steps) {
return steps * 0.04;
}
}
public class health{
public static void main(String[] args) {
HealthTracker user1 = new HealthTracker("user123");
System.out.println("User ID: " + user1.getUserId());
System.out.println("Steps Taken: " + user1.getStepsTaken());
System.out.println("Calories Burned: " + user1.getCaloriesBurned());
user1.setStepsTaken(5000);
System.out.println("\nAfter tracking 5000 steps:");
System.out.println("Steps Taken: " + user1.getStepsTaken());
System.out.println("Calories Burned: " + user1.getCaloriesBurned());
user1.setStepsTaken(-100);
}
}
OUTPUT:
5. Abstraction
Scenario: Create an abstract class Appliance with an abstract method turnOn(). Derive two subclasses
WashingMachine and Refrigerator, each providing specific implementation for the turnOn() method.
Demonstrate abstraction by turning on these appliances.
PROGRAM:
abstract class Appliance {
public abstract void turnOn();}
class WashingMachine extends Appliance {
public void turnOn() {
System.out.println("The washing machine is now running...");}
}
class Refrigerator extends Appliance {
public void turnOn() {
System.out.println("The refrigerator is now cooling...");}
}
public class appliances{
public static void main(String[] args) {
Appliance washingMachine = new WashingMachine();
Appliance refrigerator = new Refrigerator();
washingMachine.turnOn();
refrigerator.turnOn();
}
}
OUTPUT:
6. Interface
Scenario: Design a PaymentGateway interface with methods processPayment() and generateReceipt().
Implement this interface in two classes: MobilePayment and NetBanking. Create a program to process and
display payment details for each type.
PROGRAM:
interface PaymentGateway {
void processPayment(double amount);
void generateReceipt();
}
class MobilePayment implements PaymentGateway {
private double amount;
public void processPayment(double amount) {
this.amount = amount;
System.out.println("Processing mobile payment of amount: " + amount);
}
public void generateReceipt() {
System.out.println("Mobile Payment Receipt: Amount paid: " + amount);
}}
class NetBanking implements PaymentGateway {
private double amount;
public void processPayment(double amount) {
this.amount = amount;
System.out.println("Processing net banking payment of amount: " + amount);
}
public void generateReceipt() {
System.out.println("Net Banking Payment Receipt: Amount paid: " + amount);
}
}
public class payment{
public static void main(String[] args) {
PaymentGateway mobilePayment = new MobilePayment();
PaymentGateway netBanking = new NetBanking();
mobilePayment.processPayment(250.75);
mobilePayment.generateReceipt();
System.out.println();
netBanking.processPayment(1500.50);
netBanking.generateReceipt();
}
}
OUTPUT:
7. Constructor Overloading
Scenario: Design a Vehicle class with attributes brand, model, and year. Overload the constructors to allow
creating objects with varying details (e.g., with only brand, brand and model, or all attributes). Test the
constructors with different inputs.
PROGRAM:
class Vehicle {
private String brand;
private String model;
private int year;
public Vehicle(String brand) {
this.brand = brand;
this.model = "Unknown";
this.year = 0;
}
public Vehicle(String brand, String model) {
this.brand = brand;
this.model = model;
this.year = 0;
}
public Vehicle(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}
public void displayDetails() {
System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Year: " + (year == 0 ? "Unknown" : year));
System.out.println();
}
}
public class vehicles {
public static void main(String[] args) {
Vehicle vehicle1 = new Vehicle("Toyota");
Vehicle vehicle2 = new Vehicle("Honda", "Civic");
Vehicle vehicle3 = new Vehicle("Ford", "Mustang", 2022);
System.out.println("Vehicle 1 Details:");
vehicle1.displayDetails();
System.out.println("Vehicle 2 Details:");
vehicle2.displayDetails();
System.out.println("Vehicle 3 Details:");
vehicle3.displayDetails();
}
}
OUTPUT:
8. Static Keyword
Scenario: Build a class Game with a static attribute totalPlayers to track the number of players in the game and
a non-static attribute playerName for individual players. Write methods to display the total players and the
name of each player. Demonstrate the difference between static and non-static members.
PROGRAM:
class Game {
static int totalPlayers = 0;
String playerName;
public Game(String playerName) {
this.playerName = playerName;
totalPlayers++; }
public static void displayTotalPlayers() {
System.out.println("Total players in the game: " + totalPlayers);}
public void displayPlayerName() {
System.out.println("Player's name: " + playerName);}}
public class games{
public static void main(String[] args) {
Game player1 = new Game("xxx");
Game player2 = new Game("yyy");
Game player3 = new Game("zzz");
player1.displayPlayerName();
player2.displayPlayerName();
player3.displayPlayerName();
Game.displayTotalPlayers();
}
}
OUTPUT:
9. Exception Handling
Scenario: Create a FlightBooking program where users enter the flight fare. If the fare entered is less than zero,
throw and catch an IllegalArgumentException with a custom error message. Add additional checks for invalid
data types.
PROGRAM:
import java.util.Scanner;
public class flight {
public static void bookFlight(double fare) {
if (fare < 0) {
throw new IllegalArgumentException("Fare cannot be negative. Please enter a valid fare."); }
System.out.println("Flight booked successfully with a fare of: " + fare);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the flight fare: ");
try {
String input = scanner.nextLine();
double fare = Double.parseDouble(input);
bookFlight(fare);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid numeric value for the fare.");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
}
}
}
OUTPUT:
10. Aggregation and Composition
Scenario: Create a SmartHome system with a Home class containing attributes like address and a list of
connected devices. The Device class represents individual devices like Light, Thermostat, or DoorLock.
Demonstrate aggregation by showing how devices are added to the home and how their statuses are updated.
PROGRAM:
import java.util.ArrayList;
import java.util.List;
class Device {
private String name;
private boolean isOn;
public Device(String name) {
this.name = name;
this.isOn = false;
}
public void toggle() {
this.isOn = !this.isOn;
}
public boolean isOn() {
return isOn;
}
public String getName() {
return name;
}
public void displayStatus() {
System.out.println(name + " is " + (isOn ? "ON" : "OFF"));
}
}
class Light extends Device {
public Light() {
super("Light");
}
}
class Thermostat extends Device {
public Thermostat() {
super("Thermostat");
}
}
class DoorLock extends Device {
public DoorLock() {
super("DoorLock");
}
}
class Home {
private String address;
private List<Device> devices;
public Home(String address) {
this.address = address;
this.devices = new ArrayList<>();
}
public void addDevice(Device device) {
devices.add(device);
}
public void displayDevicesStatus() {
System.out.println("Devices in the home at " + address + ":");
for (Device device : devices) {
device.displayStatus();
}
}
public void updateDeviceStatus() {
for (Device device : devices) {
device.toggle();
}
}
}
public class main{
public static void main(String[] args) {
Home myHome = new Home("123 Smart St.");
Device light = new Light();
Device thermostat = new Thermostat();
Device doorLock = new DoorLock();
myHome.addDevice(light);
myHome.addDevice(thermostat);
myHome.addDevice(doorLock);
myHome.displayDevicesStatus();
System.out.println("\nToggling device statuses...");
myHome.updateDeviceStatus();
myHome.displayDevicesStatus();
}
}
OUTPUT: