Java Employee and Shape Classes
Java Employee and Shape Classes
A class called Employee, which models an employee with an ID, name and salary, is
designed as shown in the following class diagram. The method raise-Salary (percent)
increases the salary by the given percentage. Develop the Employee class and suitable
main method for demonstration.
(Class Name: employee)
package project1;
Line 1: This declares that the class employee is part of the project1 package. Java uses packages
to group related classes.
{
private int id;
private String name;
private double salary;
Lines 4-6: These are instance variables (also called fields) of the employee class. They are
marked as private, meaning they can only be accessed within this class.
{
[Link] = id;
[Link] = name;
[Link] = salary;
}
Lines 9-11: These lines inside the constructor initialize the instance variables (id, name, and
salary) using the this keyword, which refers to the current object. It differentiates between the
local parameters (id, name, salary) and the instance variables ([Link], [Link],
[Link]).
{
if (percent > 0)
Line 14: This checks if the input percentage (percent) is greater than 0. If it is positive, the salary
raise is applied.
{
1
double raiseAmount = salary * (percent / 100);
salary += raiseAmount;
raiseAmount: Calculates the amount to increase the salary by multiplying the current
salary by the percentage (divided by 100 to convert it to a decimal).
salary += raiseAmount;: Updates the employee's salary by adding the
raiseAmount to it.
[Link](name + "'s salary raised by " + percent + "%. New salary: $"
+ salary);
Line 17: If the salary was successfully raised, this line prints the employee’s name, the percentage
increase, and the updated salary.
}
else (Line 18: If the percentage is less than or equal to 0, the else block is executed.)
{
[Link]("Invalid percentage. Salary remains unchanged.");
Line 19: If an invalid percentage (e.g., negative or zero) is provided, this line prints an error message
indicating that the salary will not change.
}
}
2
[Link](10);
Line 32: This calls the raiseSalary method, passing in 10 as the percentage. It will raise the
employee's salary by 10%.
// Displaying updated employee details
[Link]("\nEmployee Details after Salary Raise:");
[Link](employee);
Lines 34-35: These lines print the updated employee details after the salary raise, again using the
toString() method to display the employee's new salary.
}
}
----------------------------------------------------------------------------------------------------------------
OUTPUT
Initial Employee Details:
Employee ID: 1, Name: Manju, Salary: $50000.0
Manju's salary raised by 10.0%. New salary: $55000.0
This output shows the initial state of the employee, the salary after a 10% raise, and the
updated employee details.
---------------------------------------------------*****-------------------------------------------------------
3
5. Develop a JAVA program to create a class named shape. Create three sub
classes namely: circle, triangle and square, each class has two member
functions named draw () and erase (). Demonstrate polymorphism concepts
by developing suitable methods, defining member data and main program.
(Inheritance & Polymorphism – Shape Class)
package project1;
Declares that this code belongs to the project1 package.
class shape
{
protected String name;
Declares a class named shape. It has a protected member variable name of type
String that holds the shape's name, accessible within the class and its subclasses.
4
public Circle(String name, double radius)
{
super(name);
[Link] = radius;
}
Constructor of the Circle class that calls the superclass constructor to initialize name and
initializes the radius of the circle.
//@Override
public void draw()
{
[Link]("Drawing a circle with radius " + radius);
}
Overridden draw method specific to Circle. It displays a message with the radius.
//@Override
public void erase()
{
[Link]("Erasing a circle with radius " + radius);
}
}
Overridden erase method specific to Circle. It displays a message with the radius.
//@Override
public void draw()
{
[Link]("Drawing a triangle with base " + base + " and height " +
height);
}
Overridden draw method specific to Triangle, displaying a message with base and height.
5
// @Override
public void erase()
{
[Link]("Erasing a triangle with base " + base + " and height " +
height);
}
}
Overridden erase method specific to Triangle, displaying a message with base and height.
Square Class
class Square extends shape
{
private double side;
Declares a Square class that extends shape. It includes a side property.
//@Override
public void draw()
{
[Link]("Drawing a square with side length " + side);
}
Overridden draw method specific to Square, displaying a message with side.
//@Override
public void erase()
{
[Link]("Erasing a square with side length " + side);
}
}
Overridden erase method specific to Square, displaying a message with side.
Loops through each shape in the shapes array, calling draw and erase on each shape. Since
draw and erase are overridden in subclasses, they display specific messages depending on
the shape type. After each shape, it prints a blank line for clarity.
This program demonstrates polymorphism: each shape type (Circle, Triangle, Square) has a
unique implementation of the draw and erase methods, yet they can all be handled uniformly
as shape objects in the array.
OUTPUT
Drawing a circle with radius 5.0
Erasing a circle with radius 5.0
1. Each shape's specific draw and erase methods are called, displaying messages that
include the unique attributes of each shape (such as radius for Circle, base and
height for Triangle, and side length for Square).
2. The blank lines in between are printed after each shape to separate their outputs for
readability.
7
6. Develop a JAVA program to create an abstract class Shape with abstract
methods calculateArea() and calculatePerimeter(). Create subclasses Circle and
Triangle that extend the Shape class and implement the respective methods to
calculate the area and perimeter of each shape. (Abstract Class)
((Go to file select project2)- Class Name: ShapeDemo)
package project2;
Declares that this code belongs to the project2 package.
Abstract Shape Class
abstract class Shape
{
abstract double calculateArea();
abstract double calculatePerimeter();
}
Declares an abstract class Shape that serves as a blueprint for various shapes.
Contains two abstract methods calculateArea() and calculatePerimeter(), which must
be implemented by any subclass of Shape.
Circle Class
class Circle extends Shape
{
private double radius;
Declares a Circle class that extends Shape. It has a private member variable radius of type
double to represent the circle's radius.
public Circle(double radius)
{
[Link] = radius;
}
Constructor for Circle, which takes the radius as a parameter and assigns it to the radius field.
// @Override
double calculateArea()
{
return [Link] * radius * radius;
}
Implementation of the calculateArea method for Circle, which calculates and returns the
area using the formula π×radiusx2.
8
//@Override
double calculatePerimeter()
{
return 2 * [Link] * radius;
}
}
Implementation of the calculatePerimeter method for Circle, which calculates and returns
the perimeter (or circumference) using the formula 2×π×radius
Triangle Class
class Triangle extends Shape
{
private double side1;
private double side2;
private double side3;
Declares a Triangle class that also extends Shape. It has three private member variables side1,
side2, and side3 of type double representing the three sides of the triangle.
// @Override
double calculateArea()
{
// Using Heron's formula to calculate the area of a triangle
double s = (side1 + side2 + side3) / 2;
return [Link](s * (s - side1) * (s - side2) * (s - side3));
}
9
//@Override
double calculatePerimeter()
{
return side1 + side2 + side3;
}
}
Implementation of calculatePerimeter for Triangle, which returns the perimeter by adding
the three sides.
OUTPUT
Circle Area: 78.53981633974483
Circle Perimeter: 31.41592653589793
Triangle Area: 6.0
Triangle Perimeter: 12.0
10
7. Develop a JAVA program to create an interface Resizable with methods
resizeWidth(int width) and resizeHeight(int height) that allow an object to be
resized. Create a class Rectangle that implements the Resizable interface and
implements the resize methods. (Resizable interface)
package project2;
This statement declares that the classes and interfaces are part of the project2 package.
//Resizable interface
interface Resizable
{
void resizeWidth(int width);
void resizeHeight(int height);
}
The Resizable interface declares two methods, resizeWidth(int width) and
resizeHeight(int height). Classes implementing this interface must provide implementations
12
The main method in ResizeDemo creates a new Rectangle object with an initial width of 10 and
height of 5.
// Displaying the original information
[Link]("Original Rectangle Info:");
[Link]();
This section displays the initial dimensions of the rectangle by calling displayInfo().
// Resizing the rectangle
[Link](15);
[Link](8);
The resizeWidth method is called with 15 as an argument, changing the width to 15. Then
resizeHeight is called with 8 as an argument, changing the height to 8. Both methods display
Explanation of Output:
A non-static method named display() that prints the message "Outer class
display method" to the console.
A nested (inner) class named Inner.
class Inner
{
void display()
{
[Link]("Inner class display method");
}
}
}
Inner Class:
Both the Outer and Inner classes have methods named display(), demonstrating
method overriding in context based on which class the method is invoked from.
1. The Inner class is a non-static inner class. To instantiate it, you first need an object
of the enclosing Outer class.
2. [Link] Inner() creates an instance of the Inner class, tied to the outer
object of the Outer class.
3. The reference [Link] inner declares the type of the inner object.
1. Nested Classes:
o The Inner class is a non-static nested class (inner class) that belongs to the
Outer class.
2. Accessing Nested Classes:
o A nested (non-static) class instance is tied to an instance of its enclosing class.
o You access it using [Link] Inner().
3. Method Context:
o The display() methods in Outer and Inner demonstrate method isolation,
where the invoked method depends on the class of the instance.
15
9. Develop a JAVA program to raise a custom exception (user defined exception)
for DivisionByZero using try, catch, throw and finally. (Custom Exception)
(Java Class Name: CustomExceptionDemo)
This program demonstrates the creation and use of a custom exception in Java, including
how to throw, catch, and handle exceptions. Here’s a detailed, line-by-line explanation of
the code:
Package Declaration
package project2;
Declares that the code belongs to the project2 package.
Flow:
catch (DivisionByZeroException e)
{
Finally Block
finally
{
[Link]("Finally block executed");
17
}
}
}
Purpose:
Custom Exceptions:
Throwing Exceptions:
Exception Propagation:
18
10. Develop a JAVA program to create a package named mypack and import
& implement it in a suitable class. (Packages)
-------------------------------------------------------------------------------------------------------------
This Java code defines a class named MyPackageClass within the mypack package. The
class contains a method to display a message and a static utility method for adding two
numbers.
Here's a detailed, line-by-line explanation:
Package Declaration
package mypack;
Class Declaration
public class MyPackageClass
{
Declares a public class named MyPackageClass.
public: Makes the class accessible from any other class, even outside the package.
displayMessage() Method
public void displayMessage()
{
[Link]("Hello from MyPackageClass in mypack package!");
}
purpose:
Details:
public: The method is accessible from other classes, even outside the package
(provided the class is imported).
void: The method does not return any value.
[Link]: Outputs the string "Hello from MyPackageClass in
mypack package!" to the console.
Defines a static utility method named addNumbers() that takes two integers, a and b,
as input and returns their sum.
Details:
public: The method is accessible from any class, provided the mypack package is
imported.
static: The method can be called directly on the class without needing an instance
of MyPackageClass.
int: The return type of the method, indicating that it returns an integer.
return a + b;: Calculates the sum of a and b and returns the result.
1. Package Declaration:
o The mypack package groups this class logically for easier organization and
namespace management.
2. Public Access Modifier:
o Both the class and its methods are declared as public, meaning they can be
accessed from other packages if the mypack package is imported.
3. Static Method:
o The addNumbers() method is static, allowing it to be called directly using the
class name (e.g., [Link](5, 3)).
4. Non-Static Method:
o The displayMessage() method is non-static, meaning you need an object of
MyPackageClass to call it.
---------------------------------------------END------------------------------------------------------------
PackageDemo class using mypack Package
Create a Package: mypack
Java Class Name: PackageDemo
---------------------------------------------------------------------------------------------------------------
This program demonstrates how to use a class from a different package (mypack) by
importing it into the current program. It creates an instance of the MyPackageClass,
calls its methods, and utilizes both static and non-static methods. Here's a detailed, line-by-
line explanation:
Package Declaration
package mypack;
This comment indicates that the MyPackageClass is defined in the mypack package.
//Main program outside the mypack folder
Import Statement
import [Link];
Purpose:
This imports the MyPackageClass from the mypack package so it can be used in the current
program.
20
Details:
Class Declaration
public class PackageDemo
{
Declares the main class PackageDemo, which contains the main method and serves as
the program's entry point.
public: Makes the class accessible from anywhere.
Main Method
public static void main(String[] args)
{
Details:
Details:
21
// Using the utility method addNumbers from MyPackageClass
Using the Static addNumbers Method
int result = [Link](5, 3);
Purpose:
Details:
Details:
OUTPUT
Hello from MyPackageClass in mypack package!
Result of adding numbers: 8
1. Package Import:
o The import [Link]; statement imports a class from a
different package, enabling its use in this program.
2. Object Creation:
o An object of MyPackageClass is created to access non-static methods like
displayMessage().
3. Static Method Usage:
o Static methods like addNumbers() can be directly invoked using the class
name (MyPackageClass).
4. Encapsulation Across Packages:
o The program demonstrates the modularity and reusability provided by
organizing classes in different packages.
22
11. Write a program to illustrate creation of threads using runnable class.
(start method start each of the newly created thread. Inside the run method
there is sleep() for suspend the thread for 500 milliseconds). (Runnable
Interface)
Create a Package: project11
Java Class Name: RunnableThreadExample
----------------------------------------------------------------------------------------------------------------
package project11;
Declares that the code belongs to the project11 package.
MyRunnable Class
//@Override
//@SuppressWarnings("deprecation")
public void run()
{
while (running)
{
try
{ // Suppress deprecation warning for [Link]()
[Link](500);
[Link]("Thread ID: " + [Link]().getId() + " is
running.");
}
catch (InterruptedException e)
{
[Link]("Thread interrupted.");
}
}
}
23
run() Method:
o Contains the logic executed by the thread when it starts.
Details:
o while (running): Loops continuously as long as running is true.
o [Link](500): Pauses the thread for 500 milliseconds (half
a second).
o [Link]: Prints the current thread's ID and indicates
that it's running.
o catch (InterruptedException): Handles interruptions during
sleep.
24
Creating Threads
// Create five threads and associate them with MyRunnable instances
Thread thread1 = new Thread(myRunnable1);
Thread thread2 = new Thread(myRunnable2);
Thread thread3 = new Thread(myRunnable3);
Thread thread4 = new Thread(myRunnable4);
Thread thread5 = new Thread(myRunnable5);
Purpose:
Starts each thread, which invokes the run() method of the associated MyRunnable
object.
Pauses the main thread for 500 milliseconds to allow other threads to execute and
print their messages.
Details:
Stops all five threads by calling the stopThread() method on each MyRunnable
instance.
Sets the running variable to false, causing the threads to exit the while loop and
terminate gracefully.
1. Runnable Interface:
o The MyRunnable class implements the Runnable interface, defining the
thread's behavior in the run() method.
2. Thread Creation:
o Threads are created by associating MyRunnable objects with Thread instances.
3. Concurrency:
o Multiple threads run concurrently, executing the run() method.
4. Graceful Termination:
o Threads are stopped gracefully by setting the running variable to false.
5. Volatile Keyword:
o Ensures that changes to running are immediately visible to all threads,
preventing inconsistent behavior.
--------------------------------------------*****------------------------------------------------------------
OUTPUT
Thread ID: 10 is running.
Thread ID: 11 is running.
Thread ID: 13 is running.
Thread ID: 14 is running.
Thread ID: 12 is running.
Thread ID: 10 is running.
Thread ID: 11 is running.
26
12. Develop a program to create a class MyThread in this class a
constructor, call the base class constructor, using super and start the
thread. The run method of the class starts after this. It can be observed that
both main thread and created child thread are executed concurrently.
This program demonstrates multithreading in Java by extending the Thread class. It creates a
child thread and runs it concurrently with the main thread. Here's a line-by-line explanation
of the code:
package project11;
Declares that the code belongs to the project11 package.
class MyThread extends Thread
{
Purpose:
o Defines a custom thread class by extending the Thread class.
Inheritance:
o The Thread class provides built-in methods and functionality for managing
threads.
Details:
super(name): Calls the constructor of the parent Thread class to set the thread's
name.
start(): Starts the thread, which internally calls the run() method. Starting the
thread within the constructor ensures it begins execution as soon as the object is
created.
// The run method that will be executed when the thread starts
// @Override run() Method
27
for (int i = 1; i <= 5; i++)
{
[Link]([Link]().getName() + " Count: " + i);
try
{
[Link](500); // Sleep for 500 milliseconds
}
catch (InterruptedException e)
{
[Link]([Link]().getName() + " Thread
interrupted.");
}
}
}
}
Purpose:
Details:
for Loop: Iterates from 1 to 5, printing the thread's name and the current count.
[Link]().getName(): Retrieves the name of the currently
executing thread.
[Link](500): Pauses the thread for 500 milliseconds between iterations.
Exception Handling:
o InterruptedException: Handles cases where the thread is interrupted
during sleep
Creates an instance of the MyThread class, which starts the child thread as the
start() method is called in the constructor.
Thread Name:
// Main thread
for (int i = 1; i <= 5; i++)
{
[Link]([Link]().getName() + " Thread Count: " +
i);
try
{
[Link](500); // Sleep for 500 milliseconds
}
catch (InterruptedException e)
{
[Link]([Link]().getName() + " Thread
interrupted.");
}
}
}
}
Purpose:
o The main thread executes a loop similar to the child thread, printing its name
(main) and a count from 1 to 5.
Details:
29
Key Concepts Demonstrated
1. Extending Thread:
o The MyThread class extends the Thread class, allowing it to define its own
run() method.
2. Thread Start in Constructor:
o The thread is started immediately upon object creation by calling start() in
the constructor.
3. Concurrent Execution:
o Both the main thread and the child thread execute concurrently, demonstrating
Java's multithreading capabilities.
4. Sleep and Exception Handling:
o Both threads use [Link](500) to pause briefly, ensuring their outputs
interleave.
OUTPUT
Child Thread Count: 1
main Thread Count: 1
Child Thread Count: 2
main Thread Count: 2
Child Thread Count: 3
main Thread Count: 3
main Thread Count: 4
Child Thread Count: 4
main Thread Count: 5
Child Thread Count: 5
-----------------------------------------------END----------------------------------------------------------
30