0% found this document useful (0 votes)
10 views5 pages

Final Oop 2023

Uploaded by

ibrahgriez
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)
10 views5 pages

Final Oop 2023

Uploaded by

ibrahgriez
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/ 5

QN 7. Write a program to implement class QN 6. Write a program to implement a class System.out.

println("Result: " +
Employee that has fields for employee's called Calculator that involves methods for calculator.subtract(a, b));
name, ID, and salary. The program must four basic operations.
accept all values of the mentioned fields and break;
print them in a single line of code. It must also import java.util.Scanner;
calculate a new salary after a 10% increment case '*':
of the existing salary. class Calculator {
System.out.println("Result: " +
import java.util.Scanner; public int add(int a, int b) { calculator.multiply(a, b));

class Employee { return a + b; break;

private String name; } case '/':

private int id; public int subtract(int a, int b) { System.out.println("Result: " +


calculator.divide(a, b));
private double salary; return a - b;
break;
public Employee(String name, int id, }
double salary) { default:
public int multiply(int a, int b) {
this.name = name; System.out.println("Invalid
return a * b; operator.");
this.id = id;
} break;
this.salary = salary;
public double divide(int a, int b) { }
}
if (b != 0) { } catch (ArithmeticException e) {
public void displayEmployeeInfo() {
return (double) a / b; System.out.println(e.getMessage());
System.out.println("Name: " + name + ",
} else { }
ID: " + id + ", Salary: " + salary);
throw new scanner.close();
}
ArithmeticException("Division by zero is not
public void incrementSalary() { allowed."); }

salary += salary * 0.10; } }

System.out.println("New Salary after } QN 5. (a) State the relationship between


10% increment: " + salary); CarExhibition and Class Car
public static void main(String[] args) {
} Relationship:
Scanner scanner = new
public static void main(String[] args) { Scanner(System.in); The CarExhibition class contains a collection
(ArrayList) of Car objects, indicating a
Scanner scanner = new Calculator calculator = new composition relationship where
Scanner(System.in); Calculator(); CarExhibition is composed of multiple Car
objects. Car is the superclass for ClassicCar
System.out.print("Enter Employee System.out.print("Enter first integer: "); and SportCar.
Name: ");
int a = scanner.nextInt(); (b) Write a program to implement the above
String name = scanner.nextLine(); representation
System.out.print("Enter second integer:
System.out.print("Enter Employee ID: "); import java.util.ArrayList;
");
int b = scanner.nextInt(); abstract class Car {
int id = scanner.nextInt();
System.out.print("Choose operation (+, protected double price;
System.out.print("Enter Employee -, *, /): ");
Salary: "); protected int year;
char operator =
double salary = scanner.nextDouble(); scanner.next().charAt(0); public Car(double price, int year) {

Employee employee = new try { this.price = price;


Employee(name, id, salary);
switch (operator) { this.year = year;
employee.displayEmployeeInfo();
case '+': }
employee.incrementSalary();
System.out.println("Result: " + abstract double calculateSalePrice();
scanner.close(); calculator.add(a, b));
}
} break;
class ClassicCar extends Car {
} case '-':
public ClassicCar(double price, int year) {
super(price, year); } class Patient {

} @Override private String name;

@Override public String toString() { private int age;

double calculateSalePrice() { StringBuilder sb = new StringBuilder(); private String disease;

return 10000; for (Car car : cars) { private Date admissionDate;

} private Date dischargeDate;


sb.append(car.getClass().getSimpleName())
} public Patient(String name, int age, String
.append(" - Year: ").append(car.year) disease, Date admissionDate, Date
class SportCar extends Car { dischargeDate) {
.append(", Price:
public SportCar(double price, int year) { ").append(car.price) this.name = name;

super(price, year); .append(", Sale Price: this.age = age;


").append(car.calculateSalePrice())
} this.disease = disease;
.append("\n");
@Override this.admissionDate = admissionDate;
}
double calculateSalePrice() { this.dischargeDate = dischargeDate;
return sb.toString();
if (year > 2000) { }
}
return 0.75 * price; public void enterInformation(String name,
public static void main(String[] args) { int age, String disease, Date admissionDate,
} else if (year > 1995) { Date dischargeDate) {
CarExhibition exhibition = new
return 0.5 * price; CarExhibition(); this.name = name;

} else { exhibition.addCar(20000, 1980); this.age = age;

return 0.25 * price; exhibition.addSportCar(30000, 2005); this.disease = disease;

} exhibition.addSportCar(25000, 1998); this.admissionDate = admissionDate;

} System.out.println("Total Price of Cars this.dischargeDate = dischargeDate;


in Exhibition: " + exhibition.getTotalPrice());
} }
System.out.println("Car Details:\n" +
class CarExhibition { public void displayInformation() {
exhibition.toString());
private ArrayList<Car> cars; System.out.println("Name: " + name);
}
public CarExhibition() { System.out.println("Age: " + age);
}
cars = new ArrayList<>(); System.out.println("Disease: " +
QN 4. (a) Create a class called Patient to store
the above information. disease);
}
class Date { System.out.print("Date of Admission:
public void addCar(double price, int year)
");
{
private int year;
admissionDate.displayDate();
cars.add(new ClassicCar(price, year));
private int month;
System.out.print("Date of Discharge: ");
}
private int day;
dischargeDate.displayDate();
public void addSportCar(double price, int
public Date(int year, int month, int day) {
year) { }
this.year = year;
cars.add(new SportCar(price, year)); public static void main(String[] args) {
this.month = month;
} Date admission = new Date(2024, 1,
this.day = day; 10);
public double getTotalPrice() {
} Date discharge = new Date(2024, 1, 20);
double total = 0;
public void displayDate() { Patient patient = new Patient("John
for (Car car : cars) {
Doe", 30, "Flu", admission, discharge);
System.out.println(year + "-" + month +
total += car.calculateSalePrice();
"-" + day); patient.displayInformation();
}
} }
return total;
} }
(b) Create class Date to have the date (year, o Checks if the }
month, and day as its fields) and a method to generated number
display the date. is even by @Override
determining if the
The Date class has been included in the above double area() {
remainder when
code. divided by 2 is
return 0.5 * base * height;
zero.
QN 3. Carefully read this program then
answer the following questions: }
7. count++;

public void generateNumbers() { }


o Increments the
int count = 0; count variable by 1 class Rectangle extends Shape {
if the number is
Random rand = new Random(); even. private double length;

for (int i = 0; i < 20; i++) { 8. } private double width;

int number = rand.nextInt(10); o Closes the for loop. public Rectangle(double length, double
width) {
if (number % 2 == 0) { 9. System.out.println("Count of
Even = " + count); this.length = length;
count++;
this.width = width;
o Prints the total
} count of even
}
numbers generated
}
in the loop. @Override
System.out.println("Count of Even = " +
(b) Suggest the correct output of the program double area() {
count);
The output of the program will be a count of return length * width;
}
even numbers generated from 20 random
integers between 0 and 9 (inclusive). The }
(a) Explain the meaning of each line of code.
exact count can vary since it depends on the
1. public void generateNumbers() random number generation, but the output }
{ format will be: Count of Even = <number>.
public class Main {
QN 2. Write a program to implement three
o Declares a public
public static void main(String[] args) {
Classes called Circle, Triangle, and
method named
Rectangle.
generateNumbers Circle circle = new Circle(5);
that returns no
abstract class Shape {
value (void). Triangle triangle = new Triangle(10, 5);
abstract double area();
2. int count = 0; Rectangle rectangle = new Rectangle(8,
} 4);
o Initializes a counter
variable count to class Circle extends Shape { System.out.println("Area of Circle: " +
zero. circle.area());
private double radius;
3. Random rand = new Random(); System.out.println("Area of Triangle: "
public Circle(double radius) { + triangle.area());
o Creates an instance
of the Random this.radius = radius; System.out.println("Area of Rectangle:
class to generate " + rectangle.area());
}
random numbers.
}
@Override
4. for (int i = 0; i < 20; i++) {
}
double area() {
o Starts a for loop
QN 1. Part (i): Describe the following terms
that will iterate 20 return Math.PI * radius * radius; as used in Object-Oriented Programming
times, with the loop
counter i starting } (a) Class
from 0 and ending
at 19. } A class is a blueprint or prototype that defines
the attributes (fields) and behaviors
5. int number = rand.nextInt(10); class Triangle extends Shape { (methods) that the objects created from the
class can use. It serves as a template for
o Generates a private double base;
creating objects.
random integer
between 0 private double height;
(b) Objects
(inclusive) and 10
public Triangle(double base, double
(exclusive) and Objects are instances of a class. They
height) {
assigns it to the represent real-world entities and encapsulate
variable number. both the state (attributes) and behavior
this.base = base;
(methods) defined by the class. Each object
6. if (number % 2 == 0) { can have different values for its attributes.
this.height = height;
(c) Method } }

A method is a function defined within a class } class Dog extends Animal {


that describes the behaviors or actions that an
object can perform. Methods can manipulate public class Main { @Override
the object's attributes or perform specific
tasks. public static void main(String[] args) { void sound() {

Part (ii): Concepts of Object-Oriented Shape shape = new Circle(); System.out.println("Dog barks.");
Programming
shape.draw(); // Abstraction in action }
(a) Inheritance
} }
Inheritance is a mechanism in object-oriented
} public class Main {
programming where a new class (subclass)
inherits attributes and methods from an
(c) Data Encapsulation public static void main(String[] args) {
existing class (superclass). This promotes
code reuse and establishes a hierarchical Data encapsulation is the technique of Animal animal = new Dog();
relationship between classes. restricting access to certain details of an
object and only exposing certain parts. This is animal.sound(); // Polymorphism in
Example: action
achieved using access modifiers like private,
protected, and public.
class Animal { }
Example:
void eat() { }
class Person {
System.out.println("This animal eats Part (iii): Differences
food.");
private String name;
(a) Method Overriding and Method
} Overloading
private int age;
} Method Overriding:
public void setName(String name) {
class Dog extends Animal { Definition: Occurs when a subclass provides
this.name = name;
a specific implementation of a method
void bark() {
} already defined in its superclass.
System.out.println("The dog barks.");
public String getName() { Purpose: To allow a subclass to provide a
specific implementation for a method that is
}
return name; already defined in its superclass.
}
} Example:
public class Main {
public void setAge(int age) { class Animal {
public static void main(String[] args) {
this.age = age; void sound() {
Dog dog = new Dog();
} System.out.println("Animal makes a
dog.eat(); // Inherited method sound.");
public int getAge() {
dog.bark(); // Method of Dog class }
return age;
} }
}
} class Dog extends Animal {
}
(b) Data Abstraction @Override
(d) Polymorphism
Data abstraction is the concept of hiding the void sound() {
Polymorphism is the ability of an object to
complex implementation details of an object
take on many forms. It allows a single System.out.println("Dog barks.");
and exposing only the essential features. It
interface to represent different underlying
helps in reducing programming complexity
forms (data types). It is of two types: compile- }
and effort.
time polymorphism (method overloading)
and runtime polymorphism (method }
Example:
overriding).
Method Overloading:
abstract class Shape {
Example:
Definition: Occurs when multiple methods
abstract void draw();
class Animal { with the same name exist in the same class but
with different parameters.
}
void sound() {
Purpose: To allow a class to have more than
class Circle extends Shape {
System.out.println("Animal makes a one method having the same name if their
void draw() { sound."); parameter lists are different.

System.out.println("Drawing a circle."); } Example:


class Example { Purpose: Used to specify what a class must do private String time;
but not how it does it. It is a collection of
void display(int a) { abstract methods. private String location;

System.out.println(a); Usage: Implemented by classes using the private String subject;


implements keyword.
} public void setTime(String time) {
Example:
void display(String a) { this.time = time;
interface Animal {
System.out.println(a); }
void sound();
} public String getTime() {
}
} return time;
class Dog implements Animal {
(b) Private and Protected Access Modifiers }
public void sound() {
Private: public void setLocation(String location) {
System.out.println("Dog barks.");
Scope: The member is accessible only within this.location = location;
the class in which it is declared. }
}
Example: }
public String getLocation() {
class Example { Packages:
return location;
private int data; Purpose: Used to group related classes and
interfaces together to organize code and }
} manage namespace.
public void setSubject(String subject) {
Protected: Usage: Created using the package keyword.
this.subject = subject;
Scope: The member is accessible within the Example:
same package and subclasses in other }
packages. package com.example;
public String getSubject() {
Example: public class Example {
return subject;
class Example { // Class code
}
protected int data; }
public static void main(String[] args) {
} Part (iv): Output of the Program
Scanner scanner = new
(c) Public and Default Access Modifiers Corrected Program: Scanner(System.in);

Public: public class Test { Meeting meeting = new Meeting();

Scope: The member is accessible from any public void pupAge() { System.out.println("Enter the time of the
other class. meeting (HH:MM):");
int age = 0;
Example: meeting.setTime(scanner.nextLine());
age = age + 7;
class Example { System.out.println("Enter the location
System.out.println("Puppy age is: " + of the meeting:");
public int data; age);

} } meeting.setLocation(scanner.nextLine());

Default (Package-Private): public static void main(String[] args) { System.out.println("Enter the subject of
the meeting:");
Scope: The member is accessible only within Test test = new Test();
the same package. meeting.setSubject(scanner.nextLine());
test.pupAge();
Example: System.out.println("Meeting Details:");
}
class Example { System.out.println("Time: " +
} meeting.getTime());
int data; // No modifier means default
access Output: System.out.println("Location: " +
meeting.getLocation());
} Puppy age is: 7
System.out.println("Subject: " +
(d) Interfaces and Packages Part (v): Design a Class Called Meeting meeting.getSubject());

Interfaces: import java.util.Scanner; }

class Meeting { }

You might also like