[go: up one dir, main page]

0% found this document useful (0 votes)
45 views55 pages

LCI2023004 Vedamsh OOPS LAB Assignment

hbvighkg

Uploaded by

vedamsh25
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)
45 views55 pages

LCI2023004 Vedamsh OOPS LAB Assignment

hbvighkg

Uploaded by

vedamsh25
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
You are on page 1/ 55

Name:Vedamsh

Roll Number:LCI2023004

LIST OF ALL THE PROGRAMS:


APRIL-3:
1. Do all the programs that is explained in the class related with OOPS
concepts.
2. Implement the following case study using OOP concepts in Java. E-Book
stall: Every book has properties which includes : Book _Name,
Book_Author, Book_Count; Every Customer is having properties as:
Customer_Id, Customer_Name, Customer_Address and he can buy books
from E-Book stall. Write a Program which will display the text book name
and the remaining count of text books when a customer buys a text book.
3. Write a Java program to find Area and Circle of different shapes using
polymorphism concept.
4. Write an application to create a super class Employee with information first
name & last name and methods getFirstName(), getLastName(). Derive the
sub-classes ContractEmployee and RegularEmployee with the information
about department, designation & method displayFullName() ,
getDepartment(), getDesig() to print the salary and to set department name
& designation of the corresponding sub-class objects respectively.
5. Create an abstract class Shape which calculate the area and volume of 2-d
and 3-d shapes with methods getArea() and getVolume(). Reuse this class
to calculate the area and volume of square, circle, cube and sphere.
6. Write a program to create a class CIRCLE with one field as radius, used to
calculate the area of a Circle. Create another class RECTANGLE used to
calculate the area of the rectangle which is a subclass of CIRCLE class.
Use the concept of single inheritance such that the radius of circle class can
be re-used as length in rectangle class. Take necessary data members and
member functions for both the classes to solve this problem. All the data
members are initialised through the constructors. Show the result by
accessing the area method of both the classes through the objects of the
rectangle class.
7. Derive a class named as BOX from RECTANGLE class. Take necessary
data & member functions for this box class to calculate the volume of the
box. All the data members are initialised through the constructors. Show
the result by accessing the area method of circle and rectangle and the
volume method of box class through the objects of box class.
8. Derive a class named as CYLINDER from CIRCLE class. Take necessary
data & member functions for this class to calculate the volume of the
cylinder. Show the result by accessing the area method of circle and
rectangle through object of rectangle class and the area of circle and
volume method of cylinder class through the objects of cylinder class.
9. Design a base class called Student with two fields :- (i) Name (ii) roll
number. Derive two classes called Sports and Exam from the Student base
class. Class Sports has a field called s_grade and class Exam has a field
called e_grade which are integer fields. Derive a class called Results which
inherit from Sports and Exam. This class has a character array or string
field to represent the final result. Also it has a member function called
display which can be used to display the final result. Illustrate the usage of
these classes in main.
10. Create an abstract class Employee with methods getAmount() which
displays the amount paid to employee. Reuse this class to calculate
the amount to be paid to WeeklyEmployeed and HourlyEmployee
according to no. of hours and total hours for HourlyEmployee and
no. of weeks and total weeks for WeeklyEmployee.
11. Create an Interface payable with method getAmount (). Calculate the
amount to be paid to Invoice and Employee by implementing
Interface.
12. Create an Interface Vehicle with method getColor(), getNumber(),
getConsumption() calculate the fuel consumed, name and color for
TwoWheeler and Four Wheeler By implementing interface Vehicle.
13. Create an Interface Fare with method getAmount() to get the amount paid
for fare of travelling. Calculate the fare paid by bus and train implementing
interface Fare.
14. Create an Interface StudentFee with method getAmount(),
getFirstName(),getLastName(), getAddress(), getContact(). Calculate the
amount paid by the Hostler and NonHostler student by implementing
interface Student Fee.

APRIL-10
1. 1. Java Program to Access Super Class Method and Instance Variable Using
Super Keyword
2. 2. Java Program to Access Super Class Method and Instance Variable
without Super Keyword.
3. 3. Write Java program for the following:
a. Example for this operator and the use of this keyword.
b. Example for super keywords.
c. Example for static variables and methods.
4. Write a Java program to print the sum of two numbers by using this
keyword.
5. Derive sub-classes of ContractEmployee namely HourlyEmployee &
WeeklyEmployee with information number of hours & wages per hour,
number of weeks & wages per week respectively & method
calculateWages() to calculate their monthly salary. Also override getDesig()
method depending on the type of contract employee.
6. Create an Interface Vehicle with methods getColor(), getNumber(),
getConsumption() calculate the fuel consumed, name and colour for Two
Wheeler and Four Wheeler By implementing interface Vehicle.
7. Create an Interface Fare with method getAmount() to get the amount paid
for fare of travelling. Calculate the fare paid by bus and train implementing
interface Fare.
8. Create an Interface Student Fee with methods getAmount(),
getFirstName(), getLastName(), getAddress(), getContact(). Calculate the
amount paid by the Hostler and Non Hostler student by implementing
interface Student Fee.
9. Create your own exception class using the extends keyword. Write a
constructor for this class that takes a String argument and stores it inside
the object with a String reference. Write a method that prints out the stored
String. Create a try- catch clause to exercise your new exception.
10. Write a Java program to create a package called dept. Create four classes as
CSE, ECE, ME and CE add methods in each class which can display
subject names of your respective year. access this package classes from the
main class.

COLLECTION:
In the following collection framework perform these operation creation,
insertion, updation, deletion, iteration in Array list, linked list,vector.

DATA STRUCTURES:
Implement, create, update, insert, delete and iterate the following data structures
1) set- hash set, tree set
2) map- hash table, hash map
April 3rd Assignment:

Q1:
abstract class Vehicle {
private String name;
private int year;
public Vehicle(String name, int year) {
this.name = name;
this.year = year;
}

public abstract void startEngine();


public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}

public int getYear() {


return year;
}

public void setYear(int year) {


this.year = year;
}

public void displayInfo() {


System.out.println("Vehicle Name: " + name + ",
Year: " + year);
}
}

class Car extends Vehicle {


private String model;
public Car(String name, int year, String model) {
super(name, year);
this.model = model;
}
@Override
public void startEngine() {
System.out.println("Car " + getName() + " is
starting its engine...");
}

public String getModel() {


return model;
}
public void setModel(String model) {
this.model = model;
}

@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Model: " + model);
}
}

class Bike extends Vehicle {


private boolean isSportBike;
public Bike(String name, int year, boolean
isSportBike) {
super(name, year);
this.isSportBike = isSportBike;
}

@Override
public void startEngine() {
System.out.println("Bike " + getName() + " is
starting its engine...");
}

public boolean isSportBike() {


return isSportBike;
}

public void setSportBike(boolean sportBike) {


isSportBike = sportBike;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Is Sport Bike: " +
isSportBike);
}
}

public class OOPDemo {


public static void main(String[] args) {
Car car = new Car("Toyota", 2020, "Camry");
Bike bike = new Bike("Yamaha", 2018, true);
car.displayInfo();
car.startEngine();
System.out.println();
bike.displayInfo();
bike.startEngine();
}
}

Q2:
class Book {
private String name;
private String author;
private int count;

public Book(String name, String author, int count)


{
this.name = name;
this.author = author;
this.count = count;
}

public String getName() {


return name;
}

public int getCount() {


return count;
}

public void decreaseCount() {


count--;
}
}

class Customer {
private int id;
private String name;
private String address;

public Customer(int id, String name, String


address) {
this.id = id;
this.name = name;
this.address = address;
}

public void buyBook(Book book) {


if (book.getCount() > 0) {
System.out.println("Customer " + name + "
bought book: " + book.getName());
book.decreaseCount();
System.out.println("Remaining books
remaining of " + book.getName() + ": " +
book.getCount());
} else {
System.out.println("Sorry, " +
book.getName() + " is out of stock.");
}
}
}

public class OOPDemo {


public static void main(String[] args) {
Book book1 = new Book("Book1", "Author1", 10);
Book book2 = new Book("Book2", "Author2", 5);

Customer customer1 = new Customer(1, "Alice",


"123 Street");
Customer customer2 = new Customer(2, "Bob",
"456 Avenue");

customer1.buyBook(book1);
customer2.buyBook(book1);
customer1.buyBook(book2);
customer1.buyBook(book1);
}
}

Q3:
class OOPDemo {
static abstract class Shape {
abstract double area();
abstract double circumference();
}

static class Circle extends Shape {


double radius;

Circle(double radius) {
this.radius = radius;
}

@Override
double area() {
return Math.PI * radius * radius;
}

@Override
double circumference() {
return 2 * Math.PI * radius;
}
}

static class Rectangle extends Shape {


double length;
double width;

Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
double area() {
return length * width;
}
@Override
double circumference() {
return 2 * (length + width);
}
}

public static void main(String[] args) {


Shape circle = new Circle(5);
System.out.println("Area of Circle: " +
circle.area());
System.out.println("Circumference of Circle: "
+ circle.circumference());

Shape rectangle = new Rectangle(4, 6);


System.out.println("Area of Rectangle: " +
rectangle.area());
System.out.println("Perimeter of Rectangle: "
+ rectangle.circumference());
}
}

Q4:
class OOPDemo {
static class Employee {
private String firstName;
private String lastName;
public Employee(String firstName, String
lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

public String getFirstName() {


return firstName;
}

public String getLastName() {


return lastName;
}
}

static class ContractEmployee extends Employee {


private String department;
private String designation;

public ContractEmployee(String firstName,


String lastName) {
super(firstName, lastName);
}

public String getDepartment() {


return department;
}

public String getDesignation() {


return designation;
}

public void setDepartment(String department) {


this.department = department;
}
public void setDesignation(String designation)
{
this.designation = designation;
}

public void displayFullName() {


System.out.println("Full Name: " +
getFirstName() + " " + getLastName());
}
}

static class RegularEmployee extends Employee {


private String department;
private String designation;

public RegularEmployee(String firstName,


String lastName) {
super(firstName, lastName);
}

public String getDepartment() {


return department;
}

public String getDesignation() {


return designation;
}

public void setDepartment(String department) {


this.department = department;
}
public void setDesignation(String designation)
{
this.designation = designation;
}

public void displayFullName() {


System.out.println("Full Name: " +
getFirstName() + " " + getLastName());
}
}

public static void main(String[] args) {


ContractEmployee contractEmployee = new
ContractEmployee("John", "Doe");
contractEmployee.setDepartment("Engineering");
contractEmployee.setDesignation("Software
Developer");
System.out.println("Department: " +
contractEmployee.getDepartment());
System.out.println("Designation: " +
contractEmployee.getDesignation());
contractEmployee.displayFullName();

RegularEmployee regularEmployee = new


RegularEmployee("Jane", "Smith");
regularEmployee.setDepartment("HR");
regularEmployee.setDesignation("HR Manager");
System.out.println("Department: " +
regularEmployee.getDepartment());
System.out.println("Designation: " +
regularEmployee.getDesignation());
regularEmployee.displayFullName();
}
}
Q5:
class OOPDemo {
abstract static class Shape {
abstract double getArea();
abstract double getVolume();
}

static class Square extends Shape {


private double side;

public Square(double side) {


this.side = side;
}

@Override
double getArea() {
return side * side;
}

@Override
double getVolume() {
return 0;
}
}

static class Circle extends Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
double getArea() {
return Math.PI * radius * radius;
}

@Override
double getVolume() {
return 0;
}
}

static class Cube extends Shape {


private double side;

public Cube(double side) {


this.side = side;
}

@Override
double getArea() {
return 6 * side * side;
}

@Override
double getVolume() {
return side * side * side;
}
}

static class Sphere extends Shape {


private double radius;

public Sphere(double radius) {


this.radius = radius;
}
@Override
double getArea() {
return 4 * Math.PI * radius * radius;
}

@Override
double getVolume() {
return (4.0 / 3) * Math.PI * radius *
radius * radius;
}
}

public static void main(String[] args) {


Square square = new Square(5);
System.out.println("Area of Square: " +
square.getArea());
System.out.println("Volume of Square: " +
square.getVolume());

Circle circle = new Circle(3);


System.out.println("Area of Circle: " +
circle.getArea());
System.out.println("Volume of Circle: " +
circle.getVolume());

Cube cube = new Cube(4);


System.out.println("Area of Cube: " +
cube.getArea());
System.out.println("Volume of Cube: " +
cube.getVolume());

Sphere sphere = new Sphere(2);


System.out.println("Area of Sphere: " +
sphere.getArea());
System.out.println("Volume of Sphere: " +
sphere.getVolume());
}
}

Q6:
class Circle {
protected double radius;

public Circle(double radius) {


this.radius = radius;
}

public double getArea() {


return Math.PI * radius * radius;
}
}

class Rectangle extends Circle {


private double width;

public Rectangle(double radius, double width) {


super(radius);
this.width = width;
}

@Override
public double getArea() {
return radius * width;
}
}

public class OOPDemo {


public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 8);
System.out.println("Area of Rectangle: " +
rectangle.getArea());
}
}

Q7:
class Circle {
protected double radius;

public Circle(double radius) {


this.radius = radius;
}

public double getArea() {


return Math.PI * radius * radius;
}
}

class Rectangle extends Circle {


protected double width;
public Rectangle(double radius, double width) {
super(radius);
this.width = width;
}

@Override
public double getArea() {
return radius * width;
}
}

class Box extends Rectangle {


private double height;

public Box(double radius, double width, double


height) {
super(radius, width);
this.height = height;
}

public double getVolume() {


return radius * width * height;
}
}

public class OOPDemo {


public static void main(String[] args) {
Box box = new Box(5, 8, 10);
System.out.println("Area of Circle: " +
box.getArea());
System.out.println("Area of Rectangle: " +
box.getArea());
System.out.println("Volume of Box: " +
box.getVolume());
}
}
Q8:
class Circle {
protected double radius;

public Circle(double radius) {


this.radius = radius;
}

public double getArea() {


return Math.PI * radius * radius;
}
}

class Rectangle extends Circle {


protected double width;

public Rectangle(double radius, double width) {


super(radius);
this.width = width;
}

@Override
public double getArea() {
return radius * width;
}
}

class Cylinder extends Circle {


private double height;

public Cylinder(double radius, double height) {


super(radius);
this.height = height;
}

public double getVolume() {


return getArea() * height;
}
}

public class OOPDemo {


public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 8);
System.out.println("Area of Circle (via
Rectangle object): " + rectangle.getArea());
System.out.println("Area of Rectangle: " +
rectangle.getArea());

Cylinder cylinder = new Cylinder(5, 10);


System.out.println("Area of Circle (via
Cylinder object): " + cylinder.getArea());
System.out.println("Volume of Cylinder: " +
cylinder.getVolume());
}
}

Q9:
class Student {
protected String name;
protected int rollNumber;
public Student(String name, int rollNumber) {
this.name = name;
this.rollNumber = rollNumber;
}
}

class Sports extends Student {


protected int sGrade;

public Sports(String name, int rollNumber, int


sGrade) {
super(name, rollNumber);
this.sGrade = sGrade;
}
}

class Exam extends Student {


protected int eGrade;

public Exam(String name, int rollNumber, int


eGrade) {
super(name, rollNumber);
this.eGrade = eGrade;
}
}

class Results extends Sports {


private int eGrade;
private String finalResult;

public Results(String name, int rollNumber, int


sGrade, int eGrade, String finalResult) {
super(name, rollNumber, sGrade);
this.eGrade = eGrade;
this.finalResult = finalResult;
}
public void display() {
System.out.println("Name: " + name);
System.out.println("Roll Number: " +
rollNumber);
System.out.println("Sports Grade: " + sGrade);
System.out.println("Exam Grade: " + eGrade);
System.out.println("Final Result: " +
finalResult);
}
}

public class OOPDemo {


public static void main(String[] args) {
Results studentResult = new Results("John",
101, 85, 75, "Pass");
studentResult.display();
}
}

Q10:
abstract class Employee {
abstract double getAmount();
}

class WeeklyEmployee extends Employee {


private double salary_per_week;
private int total_weeks;
public WeeklyEmployee(double salary_per_week, int
total_weeks) {
this.salary_per_week = salary_per_week;
this.total_weeks = total_weeks;
}

@Override
double getAmount() {
return salary_per_week * total_weeks;
}
}

class HourlyEmployee extends Employee {


private double hourly_rate;
private int total_hours;

public HourlyEmployee(double hourly_rate, int


total_hours) {
this.hourly_rate = hourly_rate;
this.total_hours = total_hours;
}

@Override
double getAmount() {
return hourly_rate * total_hours;
}
}

public class OOPDemo {


public static void main(String[] args) {
WeeklyEmployee weekly_employee = new
WeeklyEmployee(500, 4);
HourlyEmployee hourly_employee = new
HourlyEmployee(10, 40);
System.out.println("Amount paid to Weekly
Employee: Rs." + weekly_employee.getAmount());
System.out.println("Amount paid to Hourly
Employee: Rs." + hourly_employee.getAmount());
}
}

Q11:
interface Payable {
double getAmount();
}

class Invoice implements Payable {


private String invoiceNumber;
private double amount;

public Invoice(String invoiceNumber, double


amount) {
this.invoiceNumber = invoiceNumber;
this.amount = amount;
}

@Override
public double getAmount() {
return amount;
}
}

class Employee implements Payable {


private String employeeId;
private double salary;
public Employee(String employeeId, double salary)
{
this.employeeId = employeeId;
this.salary = salary;
}

@Override
public double getAmount() {
return salary;
}
}

public class OOPDemo{


public static void main(String[] args) {
Invoice invoice = new Invoice("INV001", 5000);
Employee employee = new Employee("EMP001",
3000);

System.out.println("Amount to be paid to
Invoice: Rs" + invoice.getAmount());
System.out.println("Amount to be paid to
Employee: Rs" + employee.getAmount());
}
}

Q12:
interface Vehicle {
String getColor();
String getNumber();
double getConsumption();
double calculateFuelConsumed(double distance);
}

class TwoWheeler implements Vehicle {


private String name;
private String color;

public TwoWheeler(String name, String color) {


this.name = name;
this.color = color;
}

@Override
public String getColor() {
return color;
}

@Override
public String getNumber() {
return null; // Not for 2wheelerss

@Override
public double getConsumption() {
return 0; // Not for 2wheelerss
}

@Override
public double calculateFuelConsumed(double
distance) {
return distance / 50.0;
}
}
class FourWheeler implements Vehicle {
private String name;
private String color;
private String number;
private double consumption;

public FourWheeler(String name, String color,


String number, double consumption) {
this.name = name;
this.color = color;
this.number = number;
this.consumption = consumption;
}

@Override
public String getColor() {
return color;
}

@Override
public String getNumber() {
return number;
}

@Override
public double getConsumption() {
return consumption;
}

@Override
public double calculateFuelConsumed(double
distance) {
return distance / consumption;
}
}
public class OOPDemo {
public static void main(String[] args) {
TwoWheeler bike = new TwoWheeler("Honda",
"Black");
FourWheeler car = new FourWheeler("Toyota",
"White", "MH01AB1234", 15);

double distance = 100;


System.out.println("Fuel consumed by bike: " +
bike.calculateFuelConsumed(distance) + " liters");
System.out.println("Fuel consumed by car: " +
car.calculateFuelConsumed(distance) + " liters");
}
}

Q13:
interface Fare {
double getAmount();
}

class Bus implements Fare {


private double distance;
private double farepkm;

public Bus(double distance, double farepkm) {


this.distance = distance;
this.farepkm = farepkm;
}
@Override
public double getAmount() {
return distance * farepkm;
}
}

class Train implements Fare {


private double distance;
private double farepkm;

public Train(double distance, double farepkm) {


this.distance = distance;
this.farepkm = farepkm;
}

@Override
public double getAmount() {
return distance * farepkm;
}
}

public class OOPDemo {


public static void main(String[] args) {
Bus bus = new Bus(100, 2.5);
Train train = new Train(200, 3.0);

System.out.println("Amount paid for bus fare:


$" + bus.getAmount());
System.out.println("Amount paid for train
fare: $" + train.getAmount());
}
}
Q14:
interface StudentFee {
double getAmount();
String getFirstName();
String getLastName();
String getAddress();
String getContact();
}

class Hostler implements StudentFee {


private String firstName;
private String lastName;
private String address;
private String contact;
private double hostelFee;

public Hostler(String firstName, String lastName,


String address, String contact, double hostelFee) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.contact = contact;
this.hostelFee = hostelFee;
}

@Override
public double getAmount() {
return hostelFee;
}

@Override
public String getFirstName() {
return firstName;
}

@Override
public String getLastName() {
return lastName;
}

@Override
public String getAddress() {
return address;
}

@Override
public String getContact() {
return contact;
}
}

class NonHostler implements StudentFee {


private String firstName;
private String lastName;
private String address;
private String contact;
private double tuitionFee;

public NonHostler(String firstName, String


lastName, String address, String contact, double
tuitionFee) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.contact = contact;
this.tuitionFee = tuitionFee;
}

@Override
public double getAmount() {
return tuitionFee;
}

@Override
public String getFirstName() {
return firstName;
}

@Override
public String getLastName() {
return lastName;
}

@Override
public String getAddress() {
return address;
}

@Override
public String getContact() {
return contact;
}
}

public class OOPDemo{


public static void main(String[] args) {
Hostler hostler = new Hostler("John", "Doe",
"Hostel A, Campus B", "+91-1234567890", 15000);
NonHostler nonHostler = new
NonHostler("Alice", "Smith", "Apartment C, Street D",
"+91-9876543210", 10000);

System.out.println("Amount paid by hostler:


Rs." + hostler.getAmount());
System.out.println("Amount paid by non-
hostler: Rs." + nonHostler.getAmount());
}
}
April 10th Assignment:

Q1:
class SuperClass {
int num = 100;
void display() {
System.out.println("This is the display method of
SuperClass");
}
}
class SubClass extends SuperClass {
int num = 200;
void display() {
System.out.println("This is the display method of
SubClass");
}
void accessSuperMethod() {
super.display();
}
void accessSuperVariable() {
System.out.println("Value of num in SuperClass: "
+ super.num);
}
}
public class OOPDemo {
public static void main(String[] args) {
SubClass obj = new SubClass();
obj.display();
obj.accessSuperMethod();
obj.accessSuperVariable();
}
}
Q2:
class SuperClass {
int num = 100;
void display() {
System.out.println("This is the display method of
SuperClass");
}
}

class SubClass extends SuperClass {


void accessSuperMethod() {
display();
}
void accessSuperVariable() {
System.out.println("Value of num in SuperClass: "
+ num);
}
}

public class OOPDemo {


public static void main(String[] args) {
SubClass obj = new SubClass();
obj.display();
obj.accessSuperMethod();
obj.accessSuperVariable();
}
}

Q3:
class Person {
String name;
Person(String name) {
this.name = name;
}
void display() {
System.out.println("Name: " + this.name);
}
}
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
super.sound();
System.out.println("Dog barks");
}
}
class Counter {
static int count = 0;
Counter() {
count++;
}
static void displayCount() {
System.out.println("Count: " + count);
}
}
public class OOPDemo {
public static void main(String[] args) {
Person person = new Person("John");
person.display();
Dog dog = new Dog();
dog.sound();
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
Counter.displayCount();
}
}
Q4:
public class OOPDemo {
private int num1;
private int num2;
public OOPDemo(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
public int calculateSum() {
return this.num1 + this.num2;
}
public static void main(String[] args) {
OOPDemo calculator = new OOPDemo(6, 8);
int sum = calculator.calculateSum();
System.out.println("Sum of the two numbers: " +
sum);
}
}

Q5:
class ContractEmployee {
protected String firstName;
protected String lastName;
protected String department;
protected double monthlySalary;

public ContractEmployee(String firstName, String


lastName, String department) {
this.firstName = firstName;
this.lastName = lastName;
this.department = department;
}
public String getDesig() {
return "Contract Employee";
}

public void displayFullName() {


System.out.println("Full Name: " + firstName +
" " + lastName);
}
}

class HourlyEmployee extends ContractEmployee {


private int numberOfHours;
private double wagesPerHour;

public HourlyEmployee(String firstName, String


lastName, String department, int numberOfHours, double
wagesPerHour) {
super(firstName, lastName, department);
this.numberOfHours = numberOfHours;
this.wagesPerHour = wagesPerHour;
}

@Override
public String getDesig() {
return "Hourly Contract Employee";
}

public double calculateWages() {


return numberOfHours * wagesPerHour;
}
}

class WeeklyEmployee extends ContractEmployee {


private int numberOfWeeks;
private double wagesPerWeek;
public WeeklyEmployee(String firstName, String
lastName, String department, int numberOfWeeks, double
wagesPerWeek) {
super(firstName, lastName, department);
this.numberOfWeeks = numberOfWeeks;
this.wagesPerWeek = wagesPerWeek;
}

@Override
public String getDesig() {
return "Weekly Contract Employee";
}

public double calculateWages() {


return numberOfWeeks * wagesPerWeek;
}
}

public class OOPDemo {


public static void main(String[] args) {
HourlyEmployee hourlyEmployee = new
HourlyEmployee("Ram", "Reddy", "IT", 160, 10);
WeeklyEmployee weeklyEmployee = new
WeeklyEmployee("Ashish", "Yadav", "HR", 4, 500);

hourlyEmployee.displayFullName();
System.out.println("Designation: " +
hourlyEmployee.getDesig());
System.out.println("Monthly Salary: Rs " +
hourlyEmployee.calculateWages());

weeklyEmployee.displayFullName();
System.out.println("Designation: " +
weeklyEmployee.getDesig());
System.out.println("Monthly Salary: Rs" +
weeklyEmployee.calculateWages());
}
}

Q6:
interface Vehicle {
String getColor();
String getNumber();
double getConsumption();
double calculateFuelConsumed(double distance);
}

class TwoWheeler implements Vehicle {


private String name;
private String color;

public TwoWheeler(String name, String color) {


this.name = name;
this.color = color;
}

@Override
public String getColor() {
return color;
}

@Override
public String getNumber() {
return null; // Not for 2wheelerss

@Override
public double getConsumption() {
return 0; // Not for 2wheelerss
}

@Override
public double calculateFuelConsumed(double
distance) {
return distance / 50.0;
}
}

class FourWheeler implements Vehicle {


private String name;
private String color;
private String number;
private double consumption;

public FourWheeler(String name, String color,


String number, double consumption) {
this.name = name;
this.color = color;
this.number = number;
this.consumption = consumption;
}

@Override
public String getColor() {
return color;
}
@Override
public String getNumber() {
return number;
}

@Override
public double getConsumption() {
return consumption;
}

@Override
public double calculateFuelConsumed(double
distance) {
return distance / consumption;
}
}

public class OOPDemo {


public static void main(String[] args) {
TwoWheeler bike = new TwoWheeler("Honda",
"Black");
FourWheeler car = new FourWheeler("Toyota",
"White", "MH01AB1234", 15);

double distance = 100;


System.out.println("Fuel consumed by bike: " +
bike.calculateFuelConsumed(distance) + " liters");
System.out.println("Fuel consumed by car: " +
car.calculateFuelConsumed(distance) + " liters");
}
}
Q7:
interface Fare {
double getAmount();
}

class Bus implements Fare {


private double distance;
private double farepkm;

public Bus(double distance, double farepkm) {


this.distance = distance;
this.farepkm = farepkm;
}

@Override
public double getAmount() {
return distance * farepkm;
}
}

class Train implements Fare {


private double distance;
private double farepkm;

public Train(double distance, double farepkm) {


this.distance = distance;
this.farepkm = farepkm;
}

@Override
public double getAmount() {
return distance * farepkm;
}
}
public class OOPDemo {
public static void main(String[] args) {
Bus bus = new Bus(100, 2.5);
Train train = new Train(200, 3.0);

System.out.println("Amount paid for bus fare:


$" + bus.getAmount());
System.out.println("Amount paid for train
fare: $" + train.getAmount());
}
}

Q8:
interface StudentFee {
double getAmount();
String getFirstName();
String getLastName();
String getAddress();
String getContact();
}

class Hostler implements StudentFee {


private String firstName;
private String lastName;
private String address;
private String contact;
private double hostelFee;

public Hostler(String firstName, String lastName,


String address, String contact, double hostelFee) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.contact = contact;
this.hostelFee = hostelFee;
}

@Override
public double getAmount() {
return hostelFee;
}

@Override
public String getFirstName() {
return firstName;
}

@Override
public String getLastName() {
return lastName;
}

@Override
public String getAddress() {
return address;
}

@Override
public String getContact() {
return contact;
}
}

class NonHostler implements StudentFee {


private String firstName;
private String lastName;
private String address;
private String contact;
private double tuitionFee;

public NonHostler(String firstName, String


lastName, String address, String contact, double
tuitionFee) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.contact = contact;
this.tuitionFee = tuitionFee;
}

@Override
public double getAmount() {
return tuitionFee;
}

@Override
public String getFirstName() {
return firstName;
}

@Override
public String getLastName() {
return lastName;
}

@Override
public String getAddress() {
return address;
}

@Override
public String getContact() {
return contact;
}
}

public class OOPDemo{


public static void main(String[] args) {
Hostler hostler = new Hostler("John", "Doe",
"Hostel A, Campus B", "+91-1234567890", 15000);
NonHostler nonHostler = new
NonHostler("Alice", "Smith", "Apartment C, Street D",
"+91-9876543210", 10000);

System.out.println("Amount paid by hostler:


Rs." + hostler.getAmount());
System.out.println("Amount paid by non-
hostler: Rs." + nonHostler.getAmount());
}
}

Q9:
class UnderageException extends Exception {
private String message;

public UnderageException(String message) {


this.message = message;
}

public void printMessage() {


System.out.println(message);
}
}
public class OOPDemo {
public static void main(String[] args) {
int age = 15;

try {
if (age < 18) {
throw new UnderageException("Underage:
You cannot vote if you are under 18 years old.");
} else {
System.out.println("You are eligible
to vote.");
}
} catch (UnderageException e) {
e.printMessage();
}
}
}

Q10:
// File: Main.java
import dept.*;

public class Main {


public static void main(String[] args) {
CSE cse = new CSE();
ECE ece = new ECE();
ME me = new ME();
CE ce = new CE();
System.out.println("Subjects for Computer
Science and Engineering:");
cse.displaySubjects();
System.out.println("\nSubjects for Electronics
and Communication Engineering:");
ece.displaySubjects();
System.out.println("\nSubjects for Mechanical
Engineering:");
me.displaySubjects();
System.out.println("\nSubjects for Civil
Engineering:");
ce.displaySubjects();
}
}

// File: CSE.java
package dept;
public class CSE {
public void displaySubjects() {
System.out.println("Computer Science and
Engineering subjects: ");
System.out.println("1. Data Structures and
Algorithms");
System.out.println("2. Database Management
Systems");
}
}

// File: ECE.java
package dept;
public class ECE {
public void displaySubjects() {
System.out.println("Electronics and
Communication Engineering subjects: ");
System.out.println("1. Analog Electronics");
System.out.println("2. Digital Signal
Processing");

}
}
// File: ME.java
package dept;
public class ME {
public void displaySubjects() {
System.out.println("Mechanical Engineering
subjects: ");
System.out.println("1. Thermodynamics");
System.out.println("2. Fluid Mechanics");

}
}

// File: CE.java
package dept;
public class CE {
public void displaySubjects() {
System.out.println("Civil Engineering
subjects: ");
System.out.println("1. Structural Analysis");
System.out.println("2. Geotechnical
Engineering");
}
}
COLLECTION:
import java.util.*;

public class CollectionOperations {


public static void main(String[] args) {
// ArrayList
ArrayList<String> arrayList = new
ArrayList<>();
// Creation
arrayList.add("Dairy Milk");
arrayList.add("KitKat");
arrayList.add("Milkybar");
// Insertion
arrayList.add(1, "Ferrero Rocher");
// Updation
arrayList.set(2, "Snickers");
// Deletion
arrayList.remove("KitKat");
// Iteration
System.out.println("ArrayList:");
for (String chocolate : arrayList) {
System.out.println(chocolate);
}

// LinkedList
LinkedList<String> linkedList = new
LinkedList<>();
// Creation
linkedList.add("Dairy Milk");
linkedList.add("KitKat");
linkedList.add("Milkybar");
// Insertion
linkedList.add(1, "Ferrero Rocher");
// Updation
linkedList.set(2, "Snickers");
// Deletion
linkedList.remove("KitKat");
// Iteration
System.out.println("\nLinkedList:");
for (String chocolate : linkedList) {
System.out.println(chocolate);
}

// Vector
Vector<String> vector = new Vector<>();
// Creation
vector.add("Dairy Milk");
vector.add("KitKat");
vector.add("Milkybar");
// Insertion
vector.add(1, "Ferrero Rocher");
// Updation
vector.set(2, "Snickers");
// Deletion
vector.remove("KitKat");
// Iteration
System.out.println("\nVector:");
for (String chocolate : vector) {
System.out.println(chocolate);
}
}
}

DATA STRUCTURES:
import java.util.*;
public class DataStructuresExample {
public static void main(String[] args) {
// HashSet
HashSet<String> hashSet = new HashSet<>();
// Creation
hashSet.add("Chocolates");
hashSet.add("Candies");
hashSet.add("Biscuits");
// Iteration
System.out.println("HashSet:");
for (String snack : hashSet) {
System.out.println(snack);
}
// Check for a specific element
System.out.println("Contains 'Chocolates': " +
hashSet.contains("Chocolates"));
// Deletion
hashSet.remove("Candies");
System.out.println("HashSet after removing
'Candies': " + hashSet);
// TreeSet
TreeSet<String> treeSet = new TreeSet<>();
// Creation
treeSet.add("Chocolates");
treeSet.add("Candies");
treeSet.add("Biscuits");
// Iteration
System.out.println("\nTreeSet:");
for (String snack : treeSet) {
System.out.println(snack);
}
// Check for a specific element
System.out.println("Contains 'Chocolates': " +
treeSet.contains("Chocolates"));
// Deletion
treeSet.remove("Biscuits");
System.out.println("TreeSet after removing
'Biscuits': " + treeSet);
// Hashtable
Hashtable<Integer, String> hashtable = new
Hashtable<>();
// Creation
hashtable.put(10, "Chocolates");
hashtable.put(20, "Candies");
hashtable.put(30, "Biscuits");
// Iteration
System.out.println("\nHashtable:");
for (Map.Entry<Integer, String> entry :
hashtable.entrySet()) {
System.out.println(entry.getKey() + " -> "
+ entry.getValue());
}
// Check for a specific key
System.out.println("Contains key '10': " +
hashtable.containsKey(10));
// Deletion
hashtable.remove(20);
System.out.println("Hashtable after removing
key '20': " + hashtable);
// HashMap
HashMap<Integer, String> hashMap = new
HashMap<>();
// Creation
hashMap.put(100, "Chocolates");
hashMap.put(200, "Candies");
hashMap.put(300, "Biscuits");
// Iteration
System.out.println("\nHashMap:");
for (Map.Entry<Integer, String> entry :
hashMap.entrySet()) {
System.out.println(entry.getKey() + " -> "
+ entry.getValue());
}
// Check for a specific key
System.out.println("Contains key '100': " +
hashMap.containsKey(100));
// Deletion
hashMap.remove(300);
System.out.println("HashMap after removing key
'300': " + hashMap);
}
}

You might also like