0% found this document useful (0 votes)
43 views3 pages

Class Creation in EECS 183 Lab 4

The document provides instructions for completing several Java programming exercises involving object-oriented concepts like classes and objects. It includes UML diagrams and descriptions for Rectangle, Account, Fan, and Vote classes and asks students to: 1. Create Rectangle and Account classes with methods like getWidth(), deposit(), etc. and test them with client programs. 2. Develop a Fan class with properties like speed, radius, color and methods like toString() and test it. 3. Create a Vote class with methods like increment(), decrement(), clear() to count votes, and a client program with a menu to allow voting.

Uploaded by

....
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)
43 views3 pages

Class Creation in EECS 183 Lab 4

The document provides instructions for completing several Java programming exercises involving object-oriented concepts like classes and objects. It includes UML diagrams and descriptions for Rectangle, Account, Fan, and Vote classes and asks students to: 1. Create Rectangle and Account classes with methods like getWidth(), deposit(), etc. and test them with client programs. 2. Develop a Fan class with properties like speed, radius, color and methods like toString() and test it. 3. Create a Vote class with methods like increment(), decrement(), clear() to count votes, and a client program with a menu to allow voting.

Uploaded by

....
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

CT038-3-2 Object Oriented Development with Java

Lab 4 Classes and Objects


Answer the following questions.
Instructor-led Demo:
1. Write a class named Rectangle (slide No. 18, Lecture Week 4) and a main program
called RectArea (slide No. 19, Lecture Week 4) that will test the Rectangle class.
InNetbeans, follow the steps in Lab 1, Question 1 (steps a, b & c) to create a project
called RectArea. Then, type in the program on slide No. 19. Note: Always create the
main class first.
Next, in the Projects window, right click on the RectArea source package, click New
-> Java Class. In Class Name: enter the name of the class Rectangle, and click
Finish. Then, type in the program on slide No. 18.
Once you have written the codes for both classes, click to Run the main program (ie.
[Link]).
2. Write a class named Account to model accounts. The UML diagram for the class is
shown in Figure 4.0. Write a test program to test the Account class. In the client
program, create an Account object with an account ID of 1222, a balance of 20000,
and an annual interest rate of 4.5%. Use the withdraw method to withdraw $2500, use
the deposit method to deposit $3000, and print the balance and the monthly interest.
Account
-ID:int
-balance:double
-annualInterestRate:double
+Account()
+getId():int
+getBalance():double
+getAnnualInterestRate:double
+setId(id:int):void
+setBalance(bal:double):void
+setAnnualInterestRate(rate:double):void
+getMonthlyInterestRate():double
+withdraw(amount:double):void
+deposit(amount:double):void
Figure 4.0

Page 1

CT038-3-2 Object Oriented Development with Java


Exercise:
1. Write a class named Rectangle to represent rectangles. The UML diagram for the
class is shown in Figure 4.1 Suppose that all the rectangles are the same colour. Use a
static variable for colour.
Rectangle
-width:double
-height:double
-color:String
+Rectangle()
+Rectangle(w:double,
h:double, col:String)
+getWidth():double
+setWidth(w:double):v
oid
+getHeight():double
+setHeight(h:double):
void
+getColor:String
+setColor(col:String)
:void
+findArea():double
+findPerimeter():doub
le
Figure 4.1

Write a client program to test the class Rectangle. In the client program, create two
Rectangle objects. Assign width 5 and height 50 to each of the objects. Assign
colour yellow. Display the properties of the objects, their areas, and their perimeters.
2. Write a class named Fan to model fans. The properties, as shown in Figure 4.2, are
speed, on, radius, and color. You need to provide the accessor and mutator methods
for the properties, and the toString method for returning a string consisting of all
the values of all the properties in this class. Suppose the fan has three fixed speeds.
Use constants 1, 2, and 3 to denote slow, medium, and fast speed.
Fan
-speed:int
-on:Boolean
-radius:double
-color:String
//constructor
//accessor methods
//mutator methods
//toString method
Figure 4.2

Write a client program to test the Fan class. In the client program, create a Fan
object. Assign maximum speed, radius 10, color yellow, and turn it on. Display the
object by invoking its toString object.

Page 2

CT038-3-2 Object Oriented Development with Java


3. Consider the UML diagram below:
Vote
-count:int
+Count()
+getCount():int
+setCount(count:int):voi
d
+clear():void
+increment():void
+decrement():void
Figure 4.3

Develop a program called Vote that counts votes for a candidate who is running for
student body president. Develop a menu in the client program which prompts for
input from the user to vote for candidate, remove vote for candidate, or to clear all
votes for candidate. Your program should continue looping until the user types -1 to
exit the program.

Page 3

Common questions

Powered by AI

Designing a vote counting system using the Vote class requires careful consideration of data integrity and user interactions. The system must accurately count votes by ensuring that each operation—increment, decrement, and clear—is thread-safe, especially in multi-threaded environments. The user interface should guide users effectively, preventing invalid inputs and ensuring ease of use with clear instructions and feedback. Potential challenges include managing concurrent modifications if run on shared platforms and maintaining data persistence if required beyond a session. Error handling and user input validation are critical to prevent incorrect vote tallies and ensure reliability .

The Rectangle class has three main data fields: 'width' and 'height' of type double, which determine the dimensions of the rectangle, and 'color' of type String, which represents the color of the rectangle. These fields are crucial for defining the physical properties of any rectangle object. The class includes constructors for creating Rectangle objects, with or without initial dimensions and color. Accessor methods like 'getWidth', 'getHeight', and 'getColor' allow retrieving these properties, while mutator methods 'setWidth', 'setHeight', and 'setColor' allow for modifying them. The class also includes 'findArea' and 'findPerimeter' methods to calculate the area and perimeter, respectively, based on the width and height, which are essential for any geometric calculations involving the rectangle .

The Fan class promotes modularity by encapsulating the features related to a fan into a self-contained unit. It defines attributes such as 'speed', 'on', 'radius', and 'color', each with corresponding accessor and mutator methods. The use of constants for speed values makes the implementation more flexible and maintainable. The 'toString' method consolidates the fan's state into a single string representation, facilitating its use in various contexts without altering its core implementation. By separating concerns through well-defined methods, the class can be reused in different parts of an application or in different projects without modification, thereby adhering to the principles of modularity and reuse .

Encapsulation is implemented in the Account class by keeping the data fields 'ID', 'balance', and 'annualInterestRate' private, which prevents direct access from outside the class. Instead, public accessor and mutator methods are provided, such as 'getId', 'getBalance', 'setAnnualInterestRate', etc., allowing controlled access and modification of these fields. This encapsulation principle helps in protecting the integrity of the data by preventing unauthorized or inappropriate modifications, facilitates maintenance by allowing changes to how the data is represented internally without affecting external code, and enhances data security .

Using constants for fan speed—such as 1, 2, and 3 for slow, medium, and fast—improves code maintainability and readability. Constants make the code more understandable by replacing magic numbers with descriptive names, clarifying the purpose of numerical values within the codebase. This also simplifies updates, as changes to speed values can be managed from a single location, minimizing errors and ensuring uniformity. It enhances the code's readability and self-documenting nature, crucial for collaboration and future maintenance .

The constructor of the Fan class is crucial as it initializes the object's fields to a consistent and valid state. It sets the default speed, whether the fan is on or off, and assigns a default radius and color. By providing this initial setup, the constructor ensures that every Fan object starts with meaningful attributes, minimizing the risk of null references or uninitialized fields. This consistency is vital for the reliable functioning of accessor and mutator methods, and for any operations that depend on the fan's state being fully initialized .

The 'getMonthlyInterestRate' method in the Account class is significant because it calculates the monthly interest rate from the annual interest rate, reflecting a realistic and necessary financial computation. It is derived by dividing the 'annualInterestRate' by 12, allowing clients of the class to easily and accurately compute monthly interest amounts for the balance. This method abstracts the calculation logic, providing a clear interface for interaction and reducing the likelihood of errors that might arise from manually repeating calculations .

The client program for the Vote class includes a menu system that facilitates user interactions by continuously prompting the user for input to vote for a candidate, remove a vote, or clear all votes. A loop controls the flow, and it persists until the user inputs '-1', signaling termination. The use of conditionals manages the user choices, directing the program to call appropriate methods such as 'increment', 'decrement', or 'clear' on the Vote object. This demonstrates concepts like event-driven programming and control flow, where the application waits for user actions to determine subsequent operations .

In the Rectangle class, the color is a static variable, meaning it is shared across all instances of the class. This design decision implies that any change to the 'color' will affect all Rectangle objects uniformly, as they all reference the same data. This is useful when all instances share a common attribute that does not need to vary per instance, reducing memory consumption and ensuring consistency across objects. However, this also means that individual Rectangle objects cannot have different colors, limiting flexibility in scenarios where distinguishing colors would be necessary .

Method overloading in the Rectangle class enhances functionality by allowing different ways to initialize a Rectangle object. For example, an overloaded constructor may accept no parameters for default construction or parameters for custom width, height, and color. This flexibility accommodates various use cases, whether a quick test object or a specific dimension setup is needed. Implementational considerations include ensuring clear parameter distinctions to avoid conflicts and maintaining backward compatibility when modifying existing overloaded methods, ensuring the class remains robust and user-friendly .

You might also like