CS110 Lab 17:

Classes - The Basics

  1. 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.
  2. 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.
  3. 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.
  4. Instance variables are typically declared as private to promote encapsulation.
  5. A class contains constructors that are invoked to create objects from the class blueprint.
  6. 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.
  7. 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.

Exercise 1: Time Class

Construct a class Time that represents a moment in time, such as 8:30AM or 5:22PM

  1. What are the attributes that characterize a Time object?
  2. What are the operations that allow access to these attributes?
  3. Write a Time Java class.
  4. 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.


  1. 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+.
  2. What are the operations that allow access to these attributes?
  3. Write a Testscore Java class.
  4. 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.
    1. Construct a SalesItem class that stores a sales item being purchased. A SalesItem object can only be instantiated with explicit data values.
    2. 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

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

  1. What are the attributes that characterize an individual Rectangle?
  2. What are the operations that allow access to these attributes?
  3. What are the computational methods required for a typical Rectangle?
  4. Write a Rectangle Java class.
  5. Write a main() method to test the complete class and all its methods.
  6. Write an GUI application, as shown below, to interactively draw instances of Rectangle objects.
  7. 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: