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.

Slides:



Advertisements
Similar presentations
Chapter 6 Objects and Classes F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and.
Advertisements

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
ECE122 L4: Creating Objects February 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects.
Road Map Introduction to object oriented programming. Classes
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
Java Library Java provides a huge library or collection of useful programs A gold mine of well-tested code that can save you countless hours of development.
Chapter 2 storing numbers and creating objects Pages in Horstmann.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 1 CMT1000: Introduction to Programming Ed Currie Lecture 5a: Input and.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
Recitation 2 Main Method, API & Packages, Java Basics.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
The Java Programming Language
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Data Types – Reference Types Objective To understand what reference types are The need to study reference types To understand Java standard packages To.
Programming in Java (COP 2250) Lecture 9 Chengyong Yang Fall, 2005.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
More Object Concepts— Farrell, Chapter 4 Dr. Burns.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
1 Chapter 6 Programming with Objects and Classes F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
OOP Basics Classes & Methods (c) IDMS/SQL News
Object Oriented Programming Object and Classes Lecture 3 MBY.
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Chapter 5: Enhancing Classes
Yanal Alahmad Java Workshop Yanal Alahmad
2.5 Another Java Application: Adding Integers
Primitive Data, Variables, Loops (Maybe)
Chapter 4: Writing Classes
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Building Java Programs Chapter 2
Introduction to Java Programming
Object Oriented Programming in java
Building Java Programs Chapter 2
Chapter 2: Java Fundamentals cont’d
Chapter 2: Java Fundamentals cont’d
Presentation transcript:

Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3 Using Ready-Made Classes Objects as models of realitypage 2-3 Client and server, message and operationpage 4 Objects and classespage 5 Class diagrampage 6 The Car classpage 7-9 One reference assigns to anotherpage 10 The Random classpage The String classpage Packagespage Class constants and class methodspage Reading data from the userpage 20-22

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 2 Objects as Models of Reality Model – simplification of reality. Focusing on special aspects with reality. Object – a model of a thing that our problem is about. –focus on knowledge, the object does know a lot of things about itself. Examples of objects –A car has knowledge of its own license plate number, make, and model. It knows how it starts, how it drives, and how it stops. –A student knows her own student ID number, her own grades, name, birth date, and address. She knows how to get to her campus and how she will answer the questions on the test. –A meeting knows where it’s being held, who’s participating, when it starts, and when it’s scheduled to end. Later, it also knows who participated, and when it actually ended. Not just as in reality. These are models, and models are not miniatures of reality.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 3 Objects in Reality and in Programming An object in an object-oriented model is essentially different from the real object that it models. The model object –has a great deal of knowledge about itself, regardless of whether the real object is alive, dead, or abstract. –is responsible for solving a set of problems. In continuation, when we talk about objects, we mean the model objects. If we want to refer to the real objects, we say that in plain text.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 4 Client and Server, Message and Operation Client and server are roles that objects play. A client object asks for a service by sending a message to a server object. The message fires an operation by the server object. The server may, or may not, send an answer back to the client. Problem 1: State more messages that Greta may send to her car. Problem 2: Go more thoroughly into the knowledge that a student object needs to have about itself. State some messages that should be sent to a student object. client server Greta sends a message to her car: ”speedUp”

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 5 Objects and Classes An object has –state: “a condition or situation during the life of an object during which it satisfies some condition, performs some activity or waits for some event” - examples? –attributes: a named quality with a defined range of values - examples? –identity: all objects can be distinguished from each other. –behavior: the set of tasks (operations) that the object is able to perform Encapsulation is an important characteristic of objects. –Information about how an object solves tasks is hidden inside the object. –A client object only relates to the behavior that is defined for the server object. A class is a description of a set of objects that have the same attributes and same behavior in common.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 6 Class Diagram Classes are illustrated using class diagrams. Class diagrams is part of UML (Unified Modeling Language). A class describes a data type. Solve problem 2 page 55. class name attributes operations Car regNo make year speed start speedUp slowDown stop

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 7 (formal) parameters The Interface of an Object of the Car Class The interface of an object is a description of the object's behavior, that is the messages that a client may send to the object. These messages are performed as operations. The operations are programmed as methods. Here is the interface of a car object: –void start( ) –void speedUp(int increase) –void slowDown(int decrease) –void stop( ) Two of the methods have parameters. They tell us that we have to send data together with the messages. In this case the data have to be integers. The server object may return data to the client after performed the task. If this is the case, the type of this data is stated before the method name. None of these here. The void keyword tells that the server object does not return any message to the client after it has performed the task.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 8 (aktuelt) argument Using the Car Class In main() we create objects that we send messages to. main() has functions like a client object, we say that main() is a client program. First we have to create an object by using a constructor. The constructor is in the class, too. The interface of the constructor is (for example) like this: –Car(String regNo, String make, int year, int initSpeed); We create an object in this way: –Car theCarOfGreta = new Car("VD-12345", "Volvo", 1998, 0); Now we may send messages to the object (we call the methods): – theCarOfGreta.start(); – theCarOfGreta.speedUp(50); class CarTrip { public static void main(String[] args) { Car theCarOfTom = new Car("A45456", "Saab", 1995, 0); theCarOfTom.start(); theCarOfTom.speedUp(50); theCarOfTom.slowDown(20); theCarOfTom.stop(); } A complete client program: (actual) arguments

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 9 To Create (Instantiate) an Object of a Class A reference is a variable containing the address where the object is stored. For the sake of simplicity, we are using the name as if it was the name of the object, and not of a reference to it. theCarOfGreta Car theCarOfGreta = new Car(”VD-12345”, ”Volvo”, 1998, 0); class name reference name arguments reserved word to instantiate an object VD Volvo The data type of a reference is simply called a reference type. String is an example of a reference type. The other data types we have used until now belongs to the group of "primitive data types”.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 10 A Reference Is Set to Equal Another Reference Solve problem 1-4, pages theCarOfGreta theCarOfAnne In the beginning: The car objects have one reference each Then we execute the statement theCarOfGreta = theCarOfAnne; and get the following: theCarOfAnne theCarOfGreta There is no longer any reference to the other object; it’ll be removed from the memory.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 11 The Random Class client server, the randomGen object Give me a random number in the range [0..99]! 76 randomGen.nextInt(100) Random randomGen = new Random(seed); int number1 = randomGen.nextInt(limit);

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 12 A Client Program Using the Random Class import java.util.Random; // NB! class TestRandom { public static void main(String[] args) { final int limit = 100; // wants numbers in the range [0..99]. final int seed = 17; // the seed should be a prime number Random randomGen = new Random(seed); int number1 = randomGen.nextInt(limit); int number2 = randomGen.nextInt(limit); int number3 = randomGen.nextInt(limit); int number4 = randomGen.nextInt(limit); System.out.println( "Here you have four random numbers in the range [0.." + (limit - 1) + "]: " + number1 + " " + number2 + " " + number3 + " " + number4); } /* Example Run: Here you have four random numbers in the range [0..99]: */

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 13 Another Ready-Made Class: the String Class String city = "Trondheim"; is equivalent to: String city = new String("Trondheim"); Trondheim city theCarOfGreta VD Volvo here is the whole truth: theCarOfGreta VD Volvo

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 14 Some of the String Class' approx. 50 Methods String(String value) // Constructor char charAt(int position) // Returns the character in the stated position. // The positions are numbered from 0 on. int length() // Returns the number of characters in the string. String toLowerCase() // Creates a new string, equal to the original, but all in lower case. String toUpperCase() // Creates a new string, equal to the original, but all in upper case. String trim() // Creates a new string, spaces in the beginning and end are removed Methods searching for a single character or a substring. –Searching from the beginning: public int indexOf(int character) public int indexOf(int character, int fromIndex) public int indexOf(String subString) –Searching from the end: public int lastIndexOf(int character) public int lastIndexOf(int character, int fromIndex) public int lastIndexOf(String subString) public int lastIndexOf(String subString, int fromIndex)

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 15 class TestString { public static void main(String[] args) { String text = "Anne Smith"; String noTrailingOrLeadingSpaces = text.trim(); String result = "Spaces removed: " + noTrailingOrLeadingSpaces; String upper = text.toUpperCase(); result = result + "\nOnly upper case letters: " + upper; String lower = text.toLowerCase(); result = result + "\nOnly lower case letters: " + lower; char initial = text.charAt(0); result = result + "\nInitial letter: " + initial; char secondLetter = text.charAt(1); result = result + "\nSecond letter: " + secondLetter; int noOfChars = text.length(); result = result + "\nThe length of the string: " + noOfChars; System.out.println(result); } /* Example Run: Spaces removed: Anne Smith Only upper case letters: ANNE SMITH Only lower case letters: anne smith Initial letter: A Second letter: n The length of the string: 10 */ An Example Using the String Class Solve problems 1-3 pp text Anne Smith upper ANNE SMITH lower anne smith noTrailingOrLeadingSpaces Anne Smith A initial n secondLetter 10 noOfChars

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 16 Packages A package is a collection of classes. Standard packages: –graphics, audio and images –network communication –database programming Every class belongs to a package. –Most of the classes we create ourselves belong to a nameless package. –More general classes should be placed in named packages. The package name has to be the same as the name of the subdirectory where the classes are sited. The package name is a part of the class name; for example: java.util.Random. This class is in a subdirectory named util under a subdirectory with name java. The Java compiler and interpreter know where this subdirectory is placed.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 17 Using Packages To use the Random class, we write: –java.util.Random randomGen = new java.util. Random(seed); Instead of writing the whole class name every time, we may insert an import statement in the beginning of the file: –import java.util.Random; All classes in the package are available by writing: –import java.util.*; NB! You are not allowed to write: –import java.*.*; // Not allowed! Then we may write: –Random randomGen = new Random(seed); It is not necessary to use the import statement for the classes in the java.lang package.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 18 Class Constants and Class Methods in the Java Library The most usual and correct thing is to create objects, and to send messages to them – the methods are instance methods However, a library should provide a few general methods that might be used without creating objects first, so called class methods –methods for mathematical calculations (square root, sine, cosine, etc.) –methods for sorting and searching Class methods are marked with the static modifier –From the java.lang.Math class: public static double sqrt(double number) public static double sin(double number) –Example of use: double sqRoot = Math.sqrt(15678); // finding the square root of The library also contains many constants: public static final double PI // this is –Example of use: double circumference = Math.PI * 2 * radius;

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 19 Class Methods for Conversions from Text to Numbers An example of use: String text1 = "2345"; String text2 = "45.3"; int number1 = Integer.parseInt(text1); // interpreting text1 as an integer double number2 = Double.parseDouble(text2); // interpr. text2 as a decimal numeral System.out.println(number1 + " " + number2); As expected, the output is:

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 20 Reading Data from the User The javax.swing.JOptionPane class is used to input data from the user: String lengthInput = JOptionPane.showInputDialog( "The length of the wall (meters): "); String heightInput = JOptionPane.showInputDialog( "The height of the wall (meters): "); JOptionPane.showMessageDialog(null, "The area of the wall is " + area + " square meters.");

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 21 Here is the Complete Program /* * WallCalculations2.java E.L */ import javax.swing.JOptionPane; class WallCalculations2 { public static void main(String[] args) { String lengthInput = JOptionPane.showInputDialog("The length of the wall (meters): "); String heightInput = JOptionPane.showInputDialog("The height of the wall (meters): "); double length = Double.parseDouble(lengthInput); double height = Double.parseDouble(heightInput); double area = length * height; JOptionPane.showMessageDialog(null, "The area of the wall is " + area + " square meters."); System.exit(0); } /* Example Run: Length: 5.8 m Height: 2.4 m The area of the wall is square meters. */

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 3, page 22 More Examples JOptionPane.showMessageDialog(null, "The simplest message dialog"); JOptionPane.showMessageDialog(null, "To the left you see the error message icon", "The method with four parameters", JOptionPane.ERROR_MESSAGE); ImageIcon image = new ImageIcon("blue.gif"); JOptionPane.showMessageDialog(null, "A gif file with a blue square", "The method with five parameters", 0, image);