CS110 Lab 17:
Classes - The Basics
- Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance,
polymorphism, and abstraction. Encapsulation is the technique of making the fields in a class
private and providing access to the fields via public methods. This will guard against its attribute
from inappropriate access. If a field is declared private, it cannot be accessed by anyone outside the
class, thereby hiding the fields within the class. For this reason, encapsulation is also referred
to as data hiding.
- Encapsulation can be described as a protective barrier that prevents the code and data being randomly
accessed by other code defined outside the class. Access to the data and code is tightly controlled by
an interface.
- The main benefit of encapsulation is the ability to modify our implemented code without breaking the
code of others who use our code. With this feature Encapsulation gives maintainability, flexibility
and extensibility to our code.
- Instance variables are typically declared as private to promote encapsulation.
- A class contains constructors that are invoked to create objects from the class blueprint.
- There are two types of constructors: explicit and default. A class can have many constructors.
A constructor is not a method even though the structure its structure is similar. Specifically,
a constructor cannot have any return type, even void.
- You do not have to provide a constructor for your class, but you must be careful when doing this.
The compiler automatically provides a no-argument, default constructor for any class without constructors.
This default constructor will call the no-argument constructor of the superclass.
In this situation, the compiler will complain if the superclass doesn't have a no-argument
constructor so you must verify that it does. If your class has no explicit superclass,
then it has an implicit superclass of Object, which does have a no-argument constructor.
Construct a class Time that represents a moment in time, such as 8:30AM or 5:22PM
- What are the attributes that characterize a Time object?
- What are the operations that allow access to these attributes?
- Write a Time Java class.
- Write a main() method to test the complete class and its methods.
Exercise 2: Testscore Class
|
Construct a class Testscore that represents a score on an exam.
- What are the attributes that characterize a Testscore object? Consider that a test score
is a value between 0 and 100 and that it also has a letter grade assigned to it. For example,
a test score of 100 is also an A and a test score of 88 is also a B+.
- What are the operations that allow access to these attributes?
- Write a Testscore Java class.
- Write a main() method to test the complete class and its methods.
Exercise 3: SalesItem Class and SalesSlip Class
|
Examine the app shown in the image below.
Construct a SalesSlip class that records and computes the items in sales.
- Construct a SalesItem class that stores a sales item being purchased.
A SalesItem object can only be instantiated with explicit data values.
- Construct a SalesSlip class that records and computes the sales total of a list of SalesItems.
Assume the list of SalesItems will never exceed 10.
SalesItems can be added to the list one at a time.


Exercise 4:Model Playing Cards and Deck of Cards
|
- Construct a Card class that stores a playing card.
Each card in a deck has a suit and a rank.
The value of a card can be computed by a member method.
- Construct a Deck class that stores 52 Cards.
Use an array and fill the deck with Cards.
Write methods to shuffle the deck and deal a card.
Exercise 5: Rectangle Class |
In this exercise you will implement a Rectangle Class.
- What are the attributes that characterize an individual Rectangle?
- What are the operations that allow access to these attributes?
- What are the computational methods required for a typical Rectangle?
- Write a Rectangle Java class.
- Write a main() method to test the complete class and all its methods.
- Write an GUI application, as shown below, to interactively draw instances of Rectangle objects.
- As a Java object, all objects are members of the Super class Object. This means that we can call the method toString() and equals(). Test this.
Each rectangle object is added to the drawing pad one at a time.

Clicking on "Display Largest" will show only the largest rectangle drawn on the drawing pad.
Clicking on "Clear" will erase anything drawn on the canvas.

Rectangle.java
//TASK: BUILD A CLASS FOR A RECTANGLE
DrawPad.java - Complete the remaining tasks.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.JComponent;
class DrawPad extends JComponent {
// DATA MEMBERS:
// Image is the superclass of all classes that represent graphical images.
// Graphics2D is the fundamental class for rendering 2-dimensional shapes,
// text and images
Image image;
Graphics2D graphics2D;
// CLASS CONSTRUCTOR
public DrawPad() {
image = null;
graphics2D = null;
}
// MEMBER METHODS
public void paintComponent(Graphics g) {
if (image == null) {
image = createImage(getSize().width, getSize().height);
graphics2D = (Graphics2D) image.getGraphics();
clear();
}
g.drawImage(image, 0, 0, null);
}
public void clear() {
// CLEAN THE DRAWING PAD BY DRAW A WHITE RECTANGLE TO COVER THE ENTIRE
// DRAWING SURFACE
graphics2D.setPaint(Color.white);
graphics2D.fillRect(0, 0, getSize().width, getSize().height);
repaint();
}
public void drawRectangles() {
// CLEAN THE DRAWING PAD BY COVERING IT WITH WHITE PAINT
graphics2D.setPaint(Color.white);
graphics2D.fillRect(0, 0, getSize().width, getSize().height);
graphics2D.setPaint(Color.black);
// TASK: MODIFY THIS METHOD TO DRAW ALL THE RECTANGLES STORED IN THE ARRAY
repaint();
}
public void drawLargest() {
// CLEAN THE DRAWING PAD BY COVERING IT WITH WHITE PAINT
graphics2D.setPaint(Color.white);
graphics2D.fillRect(0, 0, getSize().width, getSize().height);
graphics2D.setPaint(Color.black);
// TASK: MODIFY THIS METHOD TO DRAW A RECTANGLE PASSED AS A PARAMETER
repaint();
}
}
MyApp.java - Complete the remaining tasks.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MyApp {
// DEFINE THE GUI ELEMENTS
static JLabel xLbl;
static JTextField xTxt;
static JLabel yLbl;
static JTextField yTxt;
static JLabel widthLbl;
static JTextField widthTxt;
static JLabel heightLbl;
static JTextField heightTxt;
// DEFINE THE DRAWING PAD
static DrawPad drawPad;
// TASK: CREATE AN ARRAY TO HOLD UP TO 30 RECTANGLES
public static void main(String[] args) {
// CREATE A WINDOW FRAME
JFrame windowFrame = new JFrame();
// CREATE A PANEL TO HOLD BUTTONS AND INPUT TEXTFIELDS
JPanel panel = new JPanel();
// CREATE LABELS AND TEXTFIELDS
xLbl = new JLabel("x:");
xTxt = new JTextField(5);
yLbl = new JLabel("y:");
yTxt = new JTextField(5);
widthLbl = new JLabel("width:");
widthTxt = new JTextField(5);
heightLbl = new JLabel("height:");
heightTxt = new JTextField(5);
// CREATE BUTTONS AND ASSIGN ACTIONLISTENERS
JButton addBtn = new JButton("Add Rectangle");
addBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//TASK: ADD A RECTANGLE TO THE DRAWING PAD
}
});
JButton clearBtn = new JButton("Clear");
clearBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//TASK: CLEAR THE RECTANGLES FROM THE DRAWING PAD
}
});
JButton displayMaxBtn = new JButton("Display Largest");
displayMaxBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//TASK: DISPLAY THE LARGEST RECTANGLE
}
});
// ADD LABELS, TEXTFIELDS, AND BUTTONS TO THE PANEL
panel.add(xLbl);
panel.add(xTxt);
panel.add(yLbl);
panel.add(yTxt);
panel.add(widthLbl);
panel.add(widthTxt);
panel.add(heightLbl);
panel.add(heightTxt);
panel.add(addBtn);
panel.add(clearBtn);
panel.add(displayMaxBtn);
// ADD THE PANEL TO THE BOTTOM OF THE WINDOW FRAME
windowFrame.add(panel, BorderLayout.SOUTH);
// TASK: CREATE A DRAWING PAD AND ADD IT TO THE CENTER OF THE WINDOW FRAME
// SET WINDOW FRAME SIZE AND MAKE IT VISIBLE TO THE USER
windowFrame.setSize(800, 400);
windowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
windowFrame.setVisible(true);
}
}
Additional Practice:
- In Java, a variable whose type is a class does not actually hold an object.
It holds the memory location of the object, and is therefore referred to as
object reference.
Explore this concept
by writing test code that declares a Rectangle object and passes it to a static method edit().
Allow edit() to make changes to the Rectangle object.