Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java the UML Way version 2002-04-17 Only to be used in connection with the book "Java the UML Way", by Else Lervik and.

Similar presentations


Presentation on theme: "Java the UML Way version 2002-04-17 Only to be used in connection with the book "Java the UML Way", by Else Lervik and."— Presentation transcript:

1 Java the UML Way http://www.tisip.no/JavaTheUmlWay/ version 2002-04-17 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4 Constructing Your Own Classes The Building Block Principle in programmingpage 2 Modeling classespage 3-4 The Surface classpage 5-6 Local variables, parameters, and instance variablespage 7 The Merchandise classpage 8 The contents of a class, details, rules and recommendationspage 9 - 15 Some new operatorspage 16 Graphics and appletspage 17-18 Subclasses and ”extends”page 19-21 Ready-made graphics classespage 22-23

2 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 2 The Building Block Principle in Programming By dividing the problem up into a number of pieces (classes), we can concentrate on one thing at a time. Several people can cooperate on a program. When they are each working on their own parts, they can work independently from each other. The building blocks can be tested and modified independently. If we don’t alter the interface for the class, we can change the implementation as often as we want, without affecting the other classes. If we create the building blocks carefully, we can make some of them general enough that they can be used later on.

3 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 3 Modeling Classes The Renovation case from chapter 2 –You just bought an old condominium that you’re going to renovate. You’ve decided that the bathroom, kitchen, and the electrical installations are fine. However, you want to replace the flooring in a couple of the rooms and paint and wallpaper some of them. You need to perform a number of calculations: How much paint, or wallpaper, will you need for a wall? How many square meters of parquet flooring, or other flooring, will you need for a floor? What will the renovation cost for each individual wall, each individual room, and the entire renovation project? Problems –Set up a list of objects by looking at the nouns –Work out a summary of the knowledge that will have to be stored in the system. These will become attributes to the objects. Set up a list showing the connections between the attributes and the objects. –Which calculations have to be done? –Distribute the responsibility for the calculations between the objects (may be difficult!) –Draw a class diagram.

4 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 4 A Possible Solution Every class with its own test program is programmed separately. Flooring name price widthOfFlooring getName getPricePerM getWidth getNoOfMeters getTotalPrice Wallpaper name price lengthPerRoll widthPerRoll getName getPricePerRoll getLengthPerRoll getWidthPerRoll getNoOfRolls getTotalPrice Paint name price noOfCoats noOfSqMPerLiter getName getPricePerLiter getNoOfCoats getNoOfSqMPerLiter getNoOfLiters getTotalPrice Surface name length width getName getLength getWidth getArea getCircumference

5 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 5 Client Program Testing the Surface Class class FloorCalculations { public static void main(String[] args) { /* Step 1: We instantiate an object of the class. */ Surface aFloor = new Surface("Mary's floor", 4.8, 2.3); /* Step 2: We retrieve data from the object, and we let the object perform calculations. */ String name = aFloor.getName(); double width = aFloor.getWidth(); double length = aFloor.getLength(); double area = aFloor.getArea(); double circumference = aFloor.getCircumference(); /* Step 3: We present the results on the screen for control. */ System.out.println( "Information about the floor with the name: " + name + ":"); System.out.println("Width: " + width); System.out.println("Length: " + length); System.out.println("Area: " + area); System.out.println("Circumference: " + circumference); } Surface name length width getName getLength getWidth getArea getCircumference

6 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 6 Here is the Surface Class public double getCircumference() { return 2 * (length + width); } method head method body Solve all the problems, pp. 90-91. the members of the class = variables + methods class Surface { private String name; private double length; private double width; public Surface(String initName, double initLength, double initWidth) { name = initName; length = initLength; width = initWidth; } public String getName() { return name; } public double getLength() { return length; } public double getWidth() { return width; } public double getArea() { return width * length; } public double getCircumference() { return 2 * (length + width); } instance variables instance methods instance methods Surface name length width getName getLength getWidth getArea getCircumference From the client program: Surface aFloor = new Surface("Mary's floor", 4.8, 2.3); …. double area = aFloor.getArea(); double circumference = aFloor.getCircumference(); …. System.out.println("Area: " + area); System.out.println("Circumference: " + circumference); constructor

7 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 7 Overview Local variables, parameters and instance variables Local variables are declared in a method and can only be used in the block where they are declared. Parameters function as local variables with initial values provided by the argument list in the method call. Local variables are not given any definite initial value. That’s up to the programmer. Instance variables are declared in a class, but outside all the methods. They can be used by all the methods in the class. Instance variables are automatically given initial values according to their data type. Variables of a number type get the value 0, while boolean variables get false, and variables of a reference type get the value null. Problem 1: Change the getCircumference() method such that the sum of the length and the width is stored in a local variable before the circumference is calculated and returned. Problem 2: Set up a list showing all the local variables and all the arguments in the test client program at slide 5.

8 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 8 Problem Merchandise merchandiseName merchandiseNo price per kilo witout VAT get price for an amount without VAT get price for an amount with VAT set new price Code the Merchandise class according to the class diagram at the left. Remember to create a constructor. Create a very simple client program. Look at your code and show examples of: –instance variable –instance method –parameter –argument –return statement –statement where an object is instantiated Then, solve problem 3 pp. 98-99. After this practise we'll look at more details on classes.

9 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 9 Access Modifiers - Private and Public Access modifiers control the access of classes, constructors, and members. private: access only from inside the class, for example from inside all the methods. public: access from everywhere, for example from a client program. No access modifier = package access, access only from inside the class' own package. class Surface { private String name; private double length; private double width; public Surface(String initName, double initLength, double initWidth) { name = initName; length = initLength; width = initWidth; } …. package access private access public access If a class' access level is more restrictive than the access level of a constructor or a member, it's the class' access level that will apply to the constructor/member. If not, it's the access level of the constructor/member that applies.

10 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 10 Overloading Names Several methods may have the same name if their signatures are different. –(A method's signature is the name, and the number and type of the parameters. The return type and the parameter names are not part of the signature.) Examples from the String class –int indexOf(int character) –int indexOf(int character, int fromIndex) –int indexOf(String str) –int indexOf(String str, int fromIndex) Using these methods String text = "To day it is January 4th. The daylight in Trondheim is from 09 AM to 15 PM."; int pos1 = text.indexOf('.'); // pos1 is 24 int pos2 = text.indexOf('4'); // pos2 is 21 int pos3 = text.indexOf('.', pos1 + 1); // pos3 is 74 int pos4 = text.indexOf("is"); // pos4 is 10 int pos5 = text.indexOf("is", pos4 + 1); // pos5 is 52 int pos6 = text.indexOf("is", pos5 + 1); // pos6 is -1 (=not found)

11 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 11 Constructors and Initializing Instance Variables The constructor name may be overloaded. A class may have several constructors. If we don't create any constructors ourselves, a constructor with empty parameter list and empty body is made automatically. This is the default constructor. If we create our own constructors, and we want a constructor with empty parameter list to exist, we have to create that too. Variables may be initialized in the declaration: –private String name = ""; –private double length = 5; If these variables get values in the constructor, too, it's the values got in the constructor that apply. A constructor may, but does not have to, assign values to all the instance variables.

12 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 12 Constructors in the Surface Class, Examples public Surface(String initName, double initLength, double initWidth) { name = initName; length = initLength; width = initWidth; } public Surface(double initLength) { length = initLength; } public Surface() { }

13 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 13 Instance Methods Examples: public double getCircumference() { // the return type is a primitive data type return 2 * (length + width); // returns a value that goes with the return type } public String getName() { // the return type is a reference type return name; // returns the reference to an object } public void setWidth(double newWidth) { width = newWidth; } Example, using the last method: aFloor.setWidth(5.3); // Message: ”Hi, you will have a new width of 5.3 meters!” Methods that implement operations that get instance values or calculate results from these values are called accessors (or get methods). Accessors don’t change the attributes. getCircumference() and getName() are examples. Methods that implement operations that change the attribute values are called mutators (or set methods). setWidth() is an example. A mutable class is a class that contains mutators. An immutable class is a class that only contains accessors.

14 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 14 Hiding Names Why doesn't this work? public void setLength(double length) { length = length; } The parameter is hiding the instance variable with the same name. Parameters and instance variables should have different names. Although it is possible for them to have the same names. Then we separate them by using the keyword this: public void setLength(double length) { this.length = length; } this is a reference that always points to the object the Java interpreter is busy with at any given time.

15 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 15 Programming Conventions for Classes These are recommendations, not syntax rules. Class names start with a capital letter. Variable names and method names start with lower-case letters. If the name consists of several words, a capital letter is used for the first letters of the second word and words that follow it. The underline character and $ are not used. Instance variables have the access modifier private. Constructors have the access modifier public. Methods have the access modifier public or private. Class variables and class methods are rarely used. Accessors and mutators whose jobs are to get or change an attribute have standardized names: –public void setNN(type value) // gives a value to the attribute NN –public type getNN() // gets the value for the attribute NN –public void setNN(boolean value) –public boolean isNN() In addition we have chosen to mark the parameter name in the mutator with the prefix new. Example: –public void setLength(double newLength)

16 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 16 Some New Operators increment operator ++ decrement operator -- compound assignment operators value++is the same asvalue = value + 1 value--is the same asvalue = value - 1 value += 3is the same asvalue = value + 3 value -= 3is the same asvalue = value - 3 value *= 3is the same asvalue = value * 3 value /= 3is the same asvalue = value / 3 value %= 3is the same asvalue = value % 3 Solve problem 2, page 105.

17 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 17 Graphics The screen being drawn on is divided into pixels, according to the given resolution, typical 1280 x 1024 points and 1024 x 768 points. We decide where the drawing will be by indicating x and y coordinates relative to the origin in the upper left-hand corner of the window.

18 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 18 Applets and Graphics import java.awt.*; // Graphics and Container classes import javax.swing.*; // JApplet and JPanel classes public class SimpleApplet extends JApplet { public void init() { Container content = getContentPane(); Drawing aDrawing = new Drawing(); content.add(aDrawing); } class Drawing extends JPanel { public void paintComponent(Graphics window) { super.paintComponent(window); // NB! setBackground(Color.green); window.drawString("Hello hello", 50, 50); window.drawOval(40, 30, 100, 40); } All applets have to be public subclasses to JApplet (more on this on next slide). All applets have an init() method. The browser instantiates an object of the SimpleApplet class and sends the init() message to this object. (Very different from applications where we have the main() method.) Our drawing is described in a separate class. The drawing procedure is inside the paintComponent() method.

19 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 19 Subclasses and ”extends” SimpleApplet is a subclass (extends) of JApplet: –The JApplet class describes (almost) every possible applet. –The SimpleApplet class describes only applets exactly as ours, with the green filled circle. These applets make a subset of the former, large set of applets. –Everything that is true for the large set of all applets, is also true for our special applet. The SimpleApplet class inherits all the characteristics of the JApplet class. Drawing is a subclass (extends) of the JPanel class. Every Java class is part of the Java class tree. –The Object class describes what is true for every Java object. –The other classes are subclasses of this class.

20 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 20 A segment of the Java Class Tree Object Component Container Panel Applet JApplet JComponent JPanel SimpleApplet Drawing setBackground() and getBackground() are inherited from here getContentPane() is inherited from here add() is inherited from here the superclass for all other classes the superclass for JPanel and Drawing the subclass for Object and Component

21 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 21 The Objects the Different Classes Describe Form Sets Container JComponent Panel Applet JApplet SimpleApplet JPanel Drawing

22 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 22 The java.awt.Graphics Class Some methods: void drawLine(int x1, int y1, int x2, int y2) void drawOval(int x, int y, int width, int height) void fillOval(int x, int y, int width, int height) void drawRect(int x, int y, int width, int height) void fillRect(int x, int y, int width, int height) void drawString(String text, int x, int y) void setFont(Font newFont) void setColor(Color newColor) Font getFont() Color getColor()

23 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002 The Research Foundation TISIP, http://tisip.no/engelsk/ Chapter 4, page 23 Classes for Colors and Fonts The java.awt.Color class Example: Color color = Color.gray; color = color.brighter(); window.setColor(color); Class Constants: Color.black Color.blue Color.cyan,... Methods: Color brighter() Color darker() The java.awt.Font class Example: Font font = new Font("Serif", Font.BOLD, 16); window.setFont(font); Constructor: Font(String name, int style, int size) Class Constants: Font.BOLD Font.ITALIC Font.PLAIN Methods: String getName() int getSize() int getStyle() boolean isBold() boolean isItalic() boolean isPlain()


Download ppt "Java the UML Way version 2002-04-17 Only to be used in connection with the book "Java the UML Way", by Else Lervik and."

Similar presentations


Ads by Google