Presentation is loading. Please wait.

Presentation is loading. Please wait.

Aalborg Media Lab 26-Jun-15 Software Design Lecture 5 “ Writing Classes”

Similar presentations


Presentation on theme: "Aalborg Media Lab 26-Jun-15 Software Design Lecture 5 “ Writing Classes”"— Presentation transcript:

1 Aalborg Media Lab 26-Jun-15 Software Design Lecture 5 “ Writing Classes”

2 Aalborg Media Lab 26-Jun-152 Writing Classes We've been using predefined classes. Now we will learn to write our own classes to define objects Chapter 4

3 Aalborg Media Lab 26-Jun-153 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

4 Aalborg Media Lab 26-Jun-154 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

5 Aalborg Media Lab 26-Jun-15 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

6 Aalborg Media Lab 26-Jun-15 Classes A class contains data declarations and method declarations int x, y; char ch; Data declarations Method declarations

7 Aalborg Media Lab 26-Jun-15 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.

8 Aalborg Media Lab 26-Jun-15 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) )

9 Aalborg Media Lab 26-Jun-15 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

10 Aalborg Media Lab 26-Jun-15 Instance Data faceValue 5 coin1 int faceValue; class Die faceValue 4 coin2

11 Aalborg Media Lab 26-Jun-15 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

12 Aalborg Media Lab 26-Jun-15 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

13 Aalborg Media Lab 26-Jun-15 UML Class Diagrams A UML class diagram for the RollingDice program: RollingDice main (args : String[]) : void Die faceValue : int roll() : int setFaceValue(int value) : void getFaceValue():int toString() : String

14 Aalborg Media Lab 26-Jun-1514 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

15 Aalborg Media Lab 26-Jun-1515 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

16 Aalborg Media Lab 26-Jun-1516 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

17 Aalborg Media Lab 26-Jun-1517 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

18 Aalborg Media Lab 26-Jun-1518 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

19 Aalborg Media Lab 26-Jun-15 Visibility Modifiers publicprivate Variables Methods Violate encapsulation Enforce encapsulation Provide services to clients Support other methods in the class

20 Aalborg Media Lab 26-Jun-15 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

21 Aalborg Media Lab 26-Jun-15 myMethod(); myMethodcompute Method Control Flow The called method can be within the same class, in which case only the method name is needed

22 Aalborg Media Lab 26-Jun-15 doIt helpMe helpMe(); obj.doIt(); main Method Control Flow The called method can be part of another class or object

23 Aalborg Media Lab 26-Jun-15 Method Header A method declaration begins with a method header char calc (int num1, int num2, String message) method name return type parameter list The parameter list specifies the type and name of each parameter. The name of a parameter in the method declaration is called a formal argument

24 Aalborg Media Lab 26-Jun-15 Method Body char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } The return expression must be consistent with the return type sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing

25 Aalborg Media Lab 26-Jun-1525 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

26 Aalborg Media Lab 26-Jun-15 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");

27 Aalborg Media Lab 26-Jun-15 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

28 Aalborg Media Lab 26-Jun-15 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

29 Aalborg Media Lab 26-Jun-1529 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

30 Aalborg Media Lab 26-Jun-15 Using Objects for GUI Graphical components may also be divided into classes –JFrame JPanel –Label

31 Aalborg Media Lab 26-Jun-15 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

32 Aalborg Media Lab 26-Jun-15 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

33 Aalborg Media Lab 26-Jun-15 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

34 Aalborg Media Lab 26-Jun-15 PushCounter import 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); }

35 Aalborg Media Lab 26-Jun-15 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;

36 Aalborg Media Lab 26-Jun-15 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); }

37 Aalborg Media Lab 26-Jun-15 //*************************************************** // 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

38 Aalborg Media Lab 26-Jun-15 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


Download ppt "Aalborg Media Lab 26-Jun-15 Software Design Lecture 5 “ Writing Classes”"

Similar presentations


Ads by Google