aalborg media lab 26-jun-15 software design lecture 5 “ writing classes”

38
Aalborg Media Lab Mar 21, 2022 Software Design Lecture 5 “ Writing Classes”

Post on 21-Dec-2015

216 views

Category:

Documents


2 download

TRANSCRIPT

Aalborg Media LabApr 18, 2023

Software Design

Lecture 5

“ Writing Classes”

Aalborg Media LabApr 18, 2023 2

Writing Classes

• We've been using predefined classes. Now we will learn to write our own classes to define objects

• Chapter 4

Aalborg Media LabApr 18, 2023 3

Objects

• An object has:

– state - descriptive characteristics

– behaviors - what it can do (or what can be done to it)

• The state of dices is their current face value (1-6)

• The behavior of the dices is that it can be rolled

• Note that the behavior of the dices might change their state

Aalborg Media LabApr 18, 2023 4

Classes

• A class is a blueprint of an object

• It is the model or pattern from which objects are created

• For example, the String class is used to define String objects

• Each String object contains specific characters (its state)

• Each String object can perform services (behaviors) such as toUpperCase

Aalborg Media LabApr 18, 2023

Classes

• The String class was provided for us by the Java standard class library

• But we can also write our own classes that define specific objects that we need

• For example, suppose we want to write a program that simulates the flipping of a coin

• We can write a Die class to represent a die object

Aalborg Media LabApr 18, 2023

Classes• A class contains data declarations and method declarations

int x, y;char ch; Data declarations

Method declarations

Aalborg Media LabApr 18, 2023

The Die Class

• In our Die class we could define the following data:

– faceValue, an integer that represents the current facing value

– Max, defining the highest facing value = 6.

• We might also define the following methods:

– a Die constructor, to initialize the object

– a roll method, to roll the die, returning the result.

Aalborg Media LabApr 18, 2023

Using the Die class

– get/set methods– toString for printing

• Create a class which uses the die class– instantiate a die (Die myDie = new Die();)

– roll it (myDie.roll();)

– get the facing value (myDie.getFaceValue();)

– print it (System.out(“Value: ” + myDie) )

Aalborg Media LabApr 18, 2023

Instance Data• The faceValue variable in the Die class is

called instance data because each instance (object) of the Die class has its own

• A class declares the type of the data, but it does not reserve any memory space for it

• Every time a Die object is created, a new faceValue variable is created as well, together with a own data space

Aalborg Media LabApr 18, 2023

Instance Data

faceValue 5

coin1

int faceValue;

class Die

faceValue 4

coin2

Aalborg Media LabApr 18, 2023

Data Scope

• The scope of data is the area in a program in which that data can be used (referenced)

• Data declared at the class level can be used by all methods in that class

• Data declared within a method can be used only in that method

• Data declared within a method is called local data

Aalborg Media LabApr 18, 2023

UML Diagrams• UML stands for the Unified Modeling Language

• UML diagrams show relationships among classes and objects

• A UML class diagram consists of one or more classes, each with sections for the class name, attributes, and methods

• Lines between classes represent associations

Aalborg Media LabApr 18, 2023

UML Class Diagrams• A UML class diagram for the RollingDice

program:

RollingDice

main (args : String[]) : void

Die

faceValue : int

roll() : intsetFaceValue(int value) : voidgetFaceValue():inttoString() : String

Aalborg Media LabApr 18, 2023 14

Encapsulation• We can take one of two views of an object:

– internal - the variables the object holds and the methods that make the object useful

– external - the services that an object provides and how the object interacts

• From the external view, an object is an encapsulated entity, providing a set of specific services

• These services define the interface to the object

Aalborg Media LabApr 18, 2023 15

Encapsulation

• An object should be self-governing

• Any changes to the object's state (its variables) should be made only by that object's methods

• We should make it difficult, if not impossible, to access an object’s variables other than via its methods

• The user, or client, of an object can request its services, but it should not have to be aware of how those services are accomplished

Aalborg Media LabApr 18, 2023 16

Encapsulation

• An encapsulated object can be thought of as a black box

• Its inner workings are hidden to the client, which invokes only the interface methods

Client

Methods

Data

Aalborg Media LabApr 18, 2023 17

Visibility Modifiers• In Java, we accomplish encapsulation through the

appropriate use of visibility modifiers, a reserved word that specifies particular characteristics of a method or data value

• We've used the modifier final to define a constant

• Java has three visibility modifiers: public, protected, and private

Aalborg Media LabApr 18, 2023 18

Visibility Modifiers

• Methods that provide the object's services are usually declared with public visibility so that they can be invoked by clients

• Public methods are also called service methods

• A method created simply to assist a service method is called a support method

Aalborg Media LabApr 18, 2023

Visibility Modifiers

public private

Variables

Methods

Violateencapsulation

Enforceencapsulation

Provide servicesto clients

Support othermethods in the

class

Aalborg Media LabApr 18, 2023

Method Declarations

• A method declaration specifies the code that will be executed when the method is invoked (or called)

• When a method is invoked, the flow of control jumps to the method and executes its code

• When complete, the flow returns to the place where the method was called and continues

• The invocation may or may not return a value, depending on how the method is defined

Aalborg Media LabApr 18, 2023

myMethod();

myMethodcompute

Method Control Flow• The called method can be within the same class, in which case

only the method name is needed

Aalborg Media LabApr 18, 2023

doIt

helpMe

helpMe();

obj.doIt();

main

Method Control Flow• The called method can be part of another class or object

Aalborg Media LabApr 18, 2023

Method Header• A method declaration begins with a method header

char calc (int num1, int num2, String message)

methodname

returntype

parameter list

The parameter list specifies the typeand name of each parameter. The name of a parameter in the methoddeclaration is called a formal argument

Aalborg Media LabApr 18, 2023

Method Bodychar calc (int num1, int num2, String message)

{ int sum = num1 + num2; char result = message.charAt (sum);

return result;}

The return expression must beconsistent with the return type

sum and resultare local data

They are created each time the method is called, and are destroyed when it finishes executing

Aalborg Media LabApr 18, 2023 25

The return Statement

• The return type of a method indicates the type of value that the method sends back to the calling location

• A method that does not return a value has a void return type

• A return statement specifies the value that will be returned

return expression;

• Its expression must conform to the return type

Aalborg Media LabApr 18, 2023

Parameters• Each time a method is called, the actual parameters in the

invocation are copied into the formal parameters

char calc (int num1, int num2, String message)

{ int sum = num1 + num2; char result = message.charAt (sum);

return result;}

ch = obj.calc (25, count, "Hello");

Aalborg Media LabApr 18, 2023

Local Data• Local variables can be declared inside a method

• The formal parameters of a method create automatic local variables when the method is invoked

• When the method finishes, all local variables are destroyed

• Instance variables, declared at the class level, exists as long as the object exists

• Any method in the class can refer to instance data

Aalborg Media LabApr 18, 2023

Method Decomposition

• A method should be relatively small, so that it can be understood as a single entity

• A potentially large method should be decomposed into several smaller methods as needed for clarity

• A service method of an object may call one or more support methods to accomplish its goal

• Support methods could call other support methods if appropriate

Aalborg Media LabApr 18, 2023 29

Constructors Revisited• Recall that a constructor is a special method that is used to

initialize a newly created object

• When writing a constructor, remember that:

– it has the same name as the class

– it does not return a value

– it has no return type, not even void

– it typically sets the initial values of instance variables

Aalborg Media LabApr 18, 2023

Using Objects for GUI

• Graphical components may also be divided into classes

– JFrame

• JPanel

– Label

– Label

Aalborg Media LabApr 18, 2023

import javax.swing.JFrame;

public class SmilingFace{public static void main (String[] args) { JFrame frame = new JFrame ("Smiling Face"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

SmilingFacePanel panel = new SmilingFacePanel();

frame.getContentPane().add(panel);

frame.pack(); frame.setVisible(true); }}

Using Objects for GUI

Aalborg Media LabApr 18, 2023

Graphical User Interfaces

• A GUI is made up of components, events that represent user actions, and listeners that respond to those events.

• TODO for general GUI:

– Instantiate all components

– Implements listener classes defining what to do on a particular event

– Creating a relationship between event-listeners and the event generating components

Aalborg Media LabApr 18, 2023

Buttons

• A button is a event generating component

• In order to work a button must be linked to a action listener

Push = new JButton;Push.addActionListener(new ButtonListener());

• ButtonListener is a custom made inner class containing the statements to be executed on the event thrown by the button

Aalborg Media LabApr 18, 2023

PushCounterimport javax.swing.JFrame;

public class PushCounter{ public static void main (String[] args) { JFrame frame = new JFrame ("Push Counter"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

frame.getContentPane().add(new PushCounterPanel()); frame.pack(); frame.setVisible(true); }}

Aalborg Media LabApr 18, 2023

PushCounterPanel 1/3//*****************************************************// PushCounterPanel.java Authors: Lewis/Loftus//// Demonstrates a GUI and an event listener.//****************************************************

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class PushCounterPanel extends JPanel{ private int count; private JButton push; private JLabel label;

Aalborg Media LabApr 18, 2023

PushCounterPanel 2/3

public PushCounterPanel () { count = 0;

push = new JButton ("Push Me!"); push.addActionListener (new ButtonListener());

label = new JLabel ("Pushes: " + count);

add (push); add (label);

setPreferredSize (new Dimension(300, 40)); setBackground (Color.cyan); }

Aalborg Media LabApr 18, 2023

//***************************************************// Represents a listener for button push events.//***************************************************

private class ButtonListener implements ActionListener {

//------------------------------------------------// Updates the counter and label when the button// is pushed.//------------------------------------------------

public void actionPerformed (ActionEvent event) { count++; label.setText("Pushes: " + count); } }}

PushCounterPanel 3/3

Aalborg Media LabApr 18, 2023

Exercises

• Compile and run listing 4.1 & 4.12• PP: 4.1

Do not count the number of two sixes that occur! Calculate the average difference between the two dices. (checkout the “ Math.abs(int) ” function)

• 4.8; 4.10