0% found this document useful (0 votes)
2 views18 pages

DCIT 201 Assignment

The document contains Java code demonstrating concepts of encapsulation, inheritance, polymorphism, and abstraction through classes such as CommissionEmployee, BasePlusCommissionEmployee, Chef, Waiter, and Student. It includes methods for calculating earnings, displaying employee details, and managing student information in a university system. The code also features error handling for invalid inputs and showcases the use of interfaces and abstract classes.

Uploaded by

zigieugene05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views18 pages

DCIT 201 Assignment

The document contains Java code demonstrating concepts of encapsulation, inheritance, polymorphism, and abstraction through classes such as CommissionEmployee, BasePlusCommissionEmployee, Chef, Waiter, and Student. It includes methods for calculating earnings, displaying employee details, and managing student information in a university system. The code also features error handling for invalid inputs and showcases the use of interfaces and abstract classes.

Uploaded by

zigieugene05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Encapsulation

Question One Code

class CommissionEmployee {

private String firstName;

private String lastName;

private String socialSecurityNumber;

private double grossSales;

private double commissionRate;

// validating constructor

public CommissionEmployee(String firstName, String lastName, String


socialSecurityNumber, double grossSales, double commissionRate) {

this.firstName = firstName;

this.lastName = lastName;

this.socialSecurityNumber = socialSecurityNumber;

setGrossSales(grossSales);

setCommissionRate(commissionRate);

// Finding Getters and Setters and validating

public String getFirstName() {

return firstName;

public void setFirstName(String firstName) {

this.firstName = firstName;

public String getLastName() {


return lastName;

public void setLastName(String lastName) {

this.lastName = lastName;

public String getSocialSecurityNumber() {

return socialSecurityNumber;

public void setSocialSecurityNumber(String socialSecurityNumber) {

this.socialSecurityNumber = socialSecurityNumber;

public double getGrossSales() {

return grossSales;

public void setGrossSales(double grossSales) {

if (grossSales < 0.0) {

throw new IllegalArgumentException("Gross sales must be >=


0.0");

this.grossSales = grossSales;

public double getCommissionRate() {

return commissionRate;
}

public void setCommissionRate(double commissionRate) {

if (commissionRate < 0.0 || commissionRate > 1.0) {

throw new IllegalArgumentException("Commission rate must be


between 0.0 and 1.0");

this.commissionRate = commissionRate;

// calculation of the earnings

public double earnings() {

return grossSales * commissionRate;

// Displaying employee details using the toString procedure

@Override

public String toString() {

return String.format("Commission Employee: %s %s\nSSN: %s\nGross


Sales: %.2f\nCommission Rate: %.2f",

firstName, lastName, socialSecurityNumber, grossSales,


commissionRate);

// Main method to test the class

public static void main(String[] args) {

try {

// Creating an employee

CommissionEmployee employee = new


CommissionEmployee("John", "Doe", "123-45-6789", 5000.0, 0.10);
System.out.println("Initial Employee Details:\n" + employee);

// Updating values

employee.setGrossSales(7000.0);

employee.setCommissionRate(0.15);

System.out.println("\nUpdated Employee Details:\n" + employee);

// Display earnings

System.out.printf("\nEarnings: %.2f\n", employee.earnings());

// Testing invalid values

System.out.println("\nTesting invalid values:");

employee.setGrossSales(-1000.0); // This should throw an


exception

} catch (IllegalArgumentException e) {

System.out.println("Exception: " + e.getMessage());

try {

CommissionEmployee employee2 = new


CommissionEmployee("Jane", "Smith", "987-65-4321", 3000.0, 1.5);

} catch (IllegalArgumentException e) {

System.out.println("Exception: " + e.getMessage());

Inheritance
Question five(5) code
import java.util.ArrayList;

import java.util.List;

// Abstracting Employee class

abstract class Employee {

protected String employeeId;

protected String name;

public Employee(String employeeId, String name) {

this.employeeId = employeeId;

this.name = name;

// Abstract method to be implemented by subclasses

public abstract void performDuty();

// subclass for chef

class Chef extends Employee {

private String specialty;

public Chef(String employeeId, String name, String specialty) {

super(employeeId, name);

this.specialty = specialty;

@Override

public void performDuty() {


System.out.println("Chef " + name + " is preparing " + specialty + "
dishes.");

// subclass for waiter

class Waiter extends Employee {

private String assignedSection;

public Waiter(String employeeId, String name, String assignedSection)


{

super(employeeId, name);

this.assignedSection = assignedSection;

@Override

public void performDuty() {

System.out.println("Waiter " + name + " is serving customers in the "


+ assignedSection + " section.");

// Restaurant Management System

class RestaurantManagementSystem {

public void assignDuty(Employee employee) {

employee.performDuty();

public static void main(String[] args) {

// Creating a Chef and a Waiter


Chef chef = new Chef("E001", "Alice", "Italian");

Waiter waiter = new Waiter("E002", "Bob", "Outdoor");

// Adding employees to a list

List<Employee> employees = new ArrayList<>();

employees.add(chef);

employees.add(waiter);

// Assigning duties

RestaurantManagementSystem system = new


RestaurantManagementSystem();

for (Employee emp : employees) {

system.assignDuty(emp);

Polymorphism
Question One(1)

public class CommissionEmployee {

private String firstName;

private String lastName;

private String socialSecurityNumber;

private double grossSales;

private double commissionRate;

// Constructor

public CommissionEmployee(String firstName, String lastName, String


socialSecurityNumber,
double grossSales, double commissionRate) {

this.firstName = firstName;

this.lastName = lastName;

this.socialSecurityNumber = socialSecurityNumber;

setGrossSales(grossSales);

setCommissionRate(commissionRate);

// Getter and Setter for grossSales with validation

public double getGrossSales() {

return grossSales;

public void setGrossSales(double grossSales) {

if (grossSales < 0) {

throw new IllegalArgumentException("Gross sales must be >= 0");

this.grossSales = grossSales;

// validating Getter and Setter for commissionRate

public double getCommissionRate() {

return commissionRate;

public void setCommissionRate(double commissionRate) {

if (commissionRate <= 0 || commissionRate >= 1) {

throw new IllegalArgumentException("Commission rate must be >


0 and < 1");
}

this.commissionRate = commissionRate;

// Earnings method

public double earnings() {

return grossSales * commissionRate;

// toString method for displaying employee info

public String toString() {

return "First Name: " + firstName + "\n" +

"Last Name: " + lastName + "\n" +

"Social Security Number: " + socialSecurityNumber + "\n" +

"Gross Sales: " + grossSales + "\n" +

"Commission Rate: " + commissionRate;

public class BasePlusCommissionEmployee extends CommissionEmployee


{

private double baseSalary;

// Constructor

public BasePlusCommissionEmployee(String firstName, String


lastName, String socialSecurityNumber,

double grossSales, double commissionRate,


double baseSalary) {
super(firstName, lastName, socialSecurityNumber, grossSales,
commissionRate);

setBaseSalary(baseSalary);

// Getter and Setter for baseSalary with validation

public double getBaseSalary() {

return baseSalary;

public void setBaseSalary(double baseSalary) {

if (baseSalary <= 0) {

throw new IllegalArgumentException("Base salary must be greater


than 0.0");

this.baseSalary = baseSalary;

// to include base salary using Overriding earnings method

@Override

public double earnings() {

return getBaseSalary() + super.earnings();

// displaying BasePlusCommissionEmployee info using toString method

@Override

public String toString() {

return super.toString() + "\n" + "Base Salary: " + baseSalary;

}
public class Main {

public static void main(String[] args) {

try {

// Create a BasePlusCommissionEmployee object using the six-


argument constructor

BasePlusCommissionEmployee employee = new


BasePlusCommissionEmployee(

"John", "Doe", "111-22-3333", 10000, 0.10, 3000);

// Displaying initial details

System.out.println("Initial Employee Info:");

System.out.println(employee);

// Update the baseSalary, grossSales, and commissionRate

employee.setBaseSalary(3500);

employee.setGrossSales(12000);

employee.setCommissionRate(0.12);

// Display updated details

System.out.println("\nUpdated Employee Info:");

System.out.println(employee);

// Calculating and displaying the total earnings

System.out.println("\nTotal Earnings: $" + employee.earnings());

// To test for invalid values

try {

employee.setBaseSalary(-1000); // Invalid base salary


} catch (IllegalArgumentException e) {

System.out.println("\nError: " + e.getMessage());

try {

employee.setGrossSales(-5000); // Invalid gross sales

} catch (IllegalArgumentException e) {

System.out.println("\nError: " + e.getMessage());

try {

employee.setCommissionRate(1.5); // Invalid commission rate

} catch (IllegalArgumentException e) {

System.out.println("\nError: " + e.getMessage());

} catch (IllegalArgumentException e) {

System.out.println("\nError: " + e.getMessage());

Abstraction
Question (5)

import java.util.ArrayList;

import java.util.Scanner;

interface Department {

// Creating interface for Department


void printDepartmentDetails();

// Class for Hostel

class Hostel {

private String hostelName;

private String hostelLocation;

private int numberOfRooms;

// setting hostel details

public void setHostelDetails(String name, String location, int rooms) {

this.hostelName = name;

this.hostelLocation = location;

this.numberOfRooms = rooms;

// printing hostel details

public void printHostelDetails() {

System.out.println("Hostel Name: " + hostelName);

System.out.println("Hostel Location: " + hostelLocation);

System.out.println("Number of Rooms: " + numberOfRooms);

// Class for Student (extends Hostel and implements Department)

class Student extends Hostel implements Department {

private String studentName;

private String regdNo;


private String electiveSubject;

private double avgMarks;

private String deptName;

private String deptHead;

// how to input student details

public void getStudentDetails() {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter Student Name: ");

this.studentName = scanner.nextLine();

System.out.print("Enter Registration Number: ");

this.regdNo = scanner.nextLine();

System.out.print("Enter Elective Subject: ");

this.electiveSubject = scanner.nextLine();

System.out.print("Enter Average Marks: ");

this.avgMarks = scanner.nextDouble();

scanner.nextLine(); // Consume newline

System.out.print("Enter Department Name: ");

this.deptName = scanner.nextLine();

System.out.print("Enter Department Head: ");

this.deptHead = scanner.nextLine();

System.out.print("Enter Hostel Name: ");

String hostelName = scanner.nextLine();

System.out.print("Enter Hostel Location: ");

String hostelLocation = scanner.nextLine();

System.out.print("Enter Number of Rooms: ");

int numberOfRooms = scanner.nextInt();

setHostelDetails(hostelName, hostelLocation, numberOfRooms);

}
// printing student details

public void printStudentDetails() {

System.out.println("Student Name: " + studentName);

System.out.println("Registration Number: " + regdNo);

System.out.println("Elective Subject: " + electiveSubject);

System.out.println("Average Marks: " + avgMarks);

printDepartmentDetails();

printHostelDetails();

// How to Implement the Department interface

@Override

public void printDepartmentDetails() {

System.out.println("Department Name: " + deptName);

System.out.println("Department Head: " + deptHead);

// Class for UniversityDriverMenu

class UniversityDriverMenu {

private ArrayList<Student> studentList = new ArrayList<>();

// admitting a new student

public void admitNewStudent() {

Student student = new Student();

student.getStudentDetails();

studentList.add(student);

System.out.println("Student admitted successfully!");


}

// migrating a student to a new hostel

public void migrateStudent() {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter Registration Number of the student to


migrate: ");

String regdNo = scanner.nextLine();

for (Student student : studentList) {

if (student.getRegdNo().equals(regdNo)) {

System.out.print("Enter New Hostel Name: ");

String hostelName = scanner.nextLine();

System.out.print("Enter New Hostel Location: ");

String hostelLocation = scanner.nextLine();

System.out.print("Enter New Number of Rooms: ");

int numberOfRooms = scanner.nextInt();

student.setHostelDetails(hostelName, hostelLocation,
numberOfRooms);

System.out.println("Hostel details updated successfully!");

return;

System.out.println("Student not found!");

// displaying student details

public void displayStudentDetails() {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter Registration Number of the student: ");

String regdNo = scanner.nextLine();


for (Student student : studentList) {

if (student.getRegdNo().equals(regdNo)) {

student.printStudentDetails();

return;

System.out.println("Student not found!");

// displaying the menu and handle user input

public void displayMenu() {

Scanner scanner = new Scanner(System.in);

while (true) {

System.out.println("\nUniversity Management System");

System.out.println("1. Admit New Student");

System.out.println("2. Migrate a Student");

System.out.println("3. Display Student Details");

System.out.println("4. Exit");

System.out.print("Enter your choice: ");

int choice = scanner.nextInt();

scanner.nextLine(); // Consume newline

switch (choice) {

case 1:

admitNewStudent();

break;

case 2:

migrateStudent();

break;
case 3:

displayStudentDetails();

break;

case 4:

System.out.println("Exiting the system. Goodbye!");

return;

default:

System.out.println("Invalid choice. Please try again.");

// Running the program using the Main Class

public class UniversityManagementSystem {

public static void main(String[] args) {

UniversityDriverMenu driver = new UniversityDriverMenu();

driver.displayMenu();

You might also like