1 / 54

Applications development with Java

Applications development with Java. Lecture 7 Rina Zviel-Girshin. object. method. Information provided to the method (parameters). Introduction to Objects. Initially, we can think of an object as a collection of services that we can tell it to perform for us

Télécharger la présentation

Applications development with Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.


Presentation Transcript

  1. Applications development with Java Lecture 7 Rina Zviel-Girshin Rina Zviel-Girshin @ASC

  2. object method Information provided to the method (parameters) Introduction to Objects • Initially, we can think of an object as a collection of services that we can tell it to perform for us • The services are defined by methods in a class that defines the object • In the many programs, we invoked the println method of the System.out object: System.out.println (“2 b or not 2 b."); Rina Zviel-Girshin @ASC

  3. Abstraction • An abstraction hides the right details at the right time • An object is abstract in that we don't really have to think about its internal details in order to use it • We don't have to know how the println or drawString methods work in order to invoke it • A human being can only manage several pieces of information at one time Rina Zviel-Girshin @ASC

  4. Abstraction • But if we group information into chunks (such as objects) we can manage many complicated pieces at once • Therefore, we can write complex software by organizing it carefully into classes and objects • That means that we can use OOP technique Rina Zviel-Girshin @ASC

  5. Software Objects • Software objects consist of data (state) and methods (operations on the data, behavior). • A program is a bunch of objects interacting with each other. • Objects are realized in programming languages (such as Java) as classes. Rina Zviel-Girshin @ASC

  6. Communication Between Objects • Relations between objects are implemented using communication (messages), you have to ‘send a message’ to ask an object to perform some action. Rina Zviel-Girshin @ASC

  7. Methods As Messages • Object’s data is useless unless we can manipulate it. • We manipulate an objects data by sending it messages. • For this purpose classes have methods. • Methods are a part of the class definition. • We interact with objects by method invocation. Rina Zviel-Girshin @ASC

  8. Method invocation • We invocate a method by using object name (object reference), “.” , method name and a pair of parenthesis. If method invocation requires additional information it is written inside the parenthesis. Point p = new Point(3,4); p.setX(0); p.setY(5); Rina Zviel-Girshin @ASC

  9. Sets of Objects • A set of objects with common characteristics and behaviors is a class (Aristotle): • All fish belong to the class of fishes • All birds belong to the class of birds • They are of the same ‘type’! Rina Zviel-Girshin @ASC

  10. Classes As New Types • The class declaration is a way of defining new types for your program – extending your language “vocabulary”. • Once a class is declared you can use it to declare object variables. • All those objects will be of the same type, they will have the same data and the same methods. Rina Zviel-Girshin @ASC

  11. Name = avi Id = 123 Address =… Move() AddGrade() Name = sara Id = 5561 Address =… Move() AddGrade() Name = ben Id = 3425 Address =… Move() AddGrade() Student Classes Class Student Name Id Address Move() AddGrade() Rina Zviel-Girshin @ASC

  12. Instances • Objects defined from a class are called also instancesof the class. • Class type, in contrast to its instance type, is the features of “all” of its objects (together) as opposite to the features of “each” of its objects (individually). Rina Zviel-Girshin @ASC

  13. OO Vocabulary • Class – a data type which describes the model or pattern of data and behavior. • Object – an instance of a class. • Method – the code body that implements an operation. • Message – request to perform an operation (a call to a method). Rina Zviel-Girshin @ASC

  14. Creating Objects • A variable either holds a primitive type, or it holds a reference to an object • A class name can be used as a type to declare an object reference variable String title; Graphics g; • No object has been created with this declaration • An object reference variable holds the address of an object • The object itself must be created separately Rina Zviel-Girshin @ASC

  15. Creating Objects • We use the new operator to create an object title = new String ("Java Software Solutions"); This calls the Stringconstructor, which is a special method that sets up the object • Creating an object is called instantiation • An object is an instance of a particular class • Objects are always initialized when they are created. The creation of some objects require additional information about their initial state. Rina Zviel-Girshin @ASC

  16. Creating Objects • Because strings are so common, we don't have to use the new operator to create a String object title = "Java Software Solutions"; • This is special syntax that only works for strings • Once an object has been instantiated, we can use the dot operator to invoke its methods title.length() Rina Zviel-Girshin @ASC

  17. Object References • Object are created in the main memory but have no name and cannot be found. • In order to interact and use them we have to assign a reference to the address of the allocated memory. • We refer to an object by means of an object reference. • An object reference holds the data about memory location of the object. Rina Zviel-Girshin @ASC

  18. x = 3 y = 4 p This variable has a type “reference to the object of type point” Object Reference Variables • Usually object references are stored in variables: InputRequestor in = new InputRequestor(); Student avi = new Student(“Avi”,1234); Point p = new Point(3,4); Rina Zviel-Girshin @ASC

  19. References Vs. Objects • An object reference and an object are two different things! • Both are stored in memory but in different places! • What can we do with references? • Define it. • Assign a new value to it. Rina Zviel-Girshin @ASC

  20. References Example Point point1 = new Point(3,4); Point point2 = new Point(1,2); References Objects Rina Zviel-Girshin @ASC

  21. References Assignment Point point1 = new Point(3,4); Point point2 = new Point(1,2); point2 = point1; int newx = point2.getx(); // newx is 3! Rina Zviel-Girshin @ASC

  22. Aliases • The assignment copies the value of the reference point1to point2. So the references refer to the same object. • Several references that refer to the same object are called aliases of each other. • Changes that are done to the object through one reference effects all aliases, because they actually refer to the same memory location! Rina Zviel-Girshin @ASC

  23. Memory Allocation • Why is it important to allocate a specific place in memory for each object? • Preserve the object state • Refer to it from different places • Not destroy it by overriding it with other data in that memory cells Rina Zviel-Girshin @ASC

  24. Cleaning Up • In previous example a reference to the original object point2 is gone. No other references refers to this memory location. • This memory location is useless, we can’t access it and can’t use it. Therefore it is sometimes called garbage. • In Java objects are automatically destroyed when they are no longer needed. Rina Zviel-Girshin @ASC

  25. Garbage Collection • Garbage collection takes care of deallocating the memory storage. • The basic idea is storage reuse: • When an object is created the memory space is allocated for this object. • Later if the object or data are not used the memory is returned to the system for future reuse. • Java language performs the garbage collection periodically automatically. Rina Zviel-Girshin @ASC

  26. new new, new… empty references x …new? …new Allocation Example Rina Zviel-Girshin @ASC

  27. Class Libraries • A class library is a collection of classes that we can use when developing programs • There is a Java standard class library that is part of any Java development environment • These classes are not part of the Java language per se, but we rely on them heavily • The System class and the String class are part of the Java standard class library • Other class libraries can be obtained through third party vendors, or you can create them yourself Rina Zviel-Girshin @ASC

  28. Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities and components Network communication Utilities Package java.lang java.applet java.awt javax.swing java.net java.util Packages • The classes of the Java standard class library are organized into packages • Some of the packages in the standard class library are: Rina Zviel-Girshin @ASC

  29. Java API (Packages) • Java comes with 3,000+ pre-designed components. • The Java API is the library of classes supplied by Java. • The classes in the Java API is separated into packages. Each package contains a set of classes that are related in some way. Rina Zviel-Girshin @ASC

  30. Documentation: Packages.html List of Packages Rina Zviel-Girshin @ASC

  31. java.lang List of Classes Rina Zviel-Girshin @ASC

  32. String Class Class Hierarchy Class Documentation Rina Zviel-Girshin @ASC

  33. String Methods Methods List Rina Zviel-Girshin @ASC

  34. The import Declaration • When you want to use a class from a package, you could use its fully qualified name java.util.Random • Or you can import the class, then just use the class name import java.util.Random; • To import all classes in a particular package, you can use the * wildcard character import java.util.*; Rina Zviel-Girshin @ASC

  35. The import Declaration • All classes of the java.lang package are automatically imported into all programs • That's why we didn't have to explicitly import the System or String classes in earlier programs • The Random class is part of the java.util package • It provides methods that generate pseudo-random numbers • We often have to scale and shift a number into an appropriate range for a particular purpose Rina Zviel-Girshin @ASC

  36. The String Class • A character string in Java is an object, defined by the String class String name = new String ("Ken Arnold"); • Because strings are so common, Java allows an abbreviated syntax: String name = "Ken Arnold"; • Java strings are immutable; once a string object has a value, it cannot be changed! Rina Zviel-Girshin @ASC

  37. String Class Example String sentence = “Houston, we have a problem.”; int length = sentence.length(); // length=27 String word = sentence.substring(0,7); //= “Houston” word = word.toLowerCase(); // word = “houston”; char c = word.charAt(2); // c =‘u’ boolean b = word.equals(“Houston”); // b=false int index = sentence.indexOf(“we”); word = sentence.substring(index, index+3); // =“we “ word = word.trim(); // word=“we” Rina Zviel-Girshin @ASC

  38. String Conversions Rina Zviel-Girshin @ASC

  39. String Conversion Example String s = "100"; int i = Integer.parseInt(s,10); long ii = Long.parseLong(s,10); s = "55.666666"; Double d_Obj = new Double(s); double d = d_Obj.doubleValue(); float f = new Float(s).floatValue(); Rina Zviel-Girshin @ASC

  40. More Conversions boolean b = false; int i=100; double d=123.45; char c=’x’; String s1=String.valueOf(b), //s1==”false” s2=String.valueOf(i), //s2==”100” s3=String.valueOf(d), //s3==”123.45” s4=String.valueOf(c); //s4==”x” Rina Zviel-Girshin @ASC

  41. The Random Class • A program may need to produce a random number (DiceSimulation.java). • TheRandomclass provides methods to simulate a random number generator. • ThenextIntmethod returns a random number from the entire spectrum ofintvalues. Usually, this number is be scaled and shifted to the desired range. Rina Zviel-Girshin @ASC

  42. Random Class Example import java.util.Random; // This program simulates a tossing of a dice class DiceSimulation { static final int NUMBER_OF_TOSSES = 10; public static void main(String[] args) { int sum; int count = 0; Random random = new Random(); Rina Zviel-Girshin @ASC

  43. Random Class Example while(count<=NUMBER_OF_TOSSES) { int result = Math.abs(random.nextInt())%6+1; sum = sum + result; } System.out.println( “The sum of tosses is “+sum); } } Rina Zviel-Girshin @ASC

  44. The StringBuffer Class • String class is immutable. • The StringBuffer class allows to use dynamic strings - which can be modified: • append(char c) • insert(int index, char c) • charAt(int index) • setCharAt(int index, char c) • reverse() • length() Rina Zviel-Girshin @ASC

  45. Class Methods • Some methods can be invoked through the class name, instead of through an object of the class • These methods are called class methods or static methods • The Math class contains many static methods, providing various mathematical functions, such as absolute value, trigonometry functions, square root, etc. temp = Math.cos(90) + Math.sqrt(delta); Rina Zviel-Girshin @ASC

  46. Applets • A Java application is a stand-alone program with a main method (like the ones we've seen so far) • An applet is a Java program that is intended to transported over the web and executed using a web browser • An applet doesn't have a main method • Instead, there are several special methods that serve specific purposes • The paint method, for instance, is automatically executed and is used to draw the applets contents Rina Zviel-Girshin @ASC

  47. Applets • The paint method accepts a parameter that is an object of the Graphics class • A Graphics object defines a graphics context on which we can draw shapes and text • The Graphics class has several methods for drawing shapes • The class that defines the applet extends the Applet class • This makes use of inheritance, an object-oriented concept we will talk about later Rina Zviel-Girshin @ASC

  48. Applets • An applet is embedded into an HTML file using a tag that references the bytecode file of the applet class • It is actually the bytecode version of the program that is transported across the web • The applet is executed by a Java interpreter that is part of the browser Rina Zviel-Girshin @ASC

  49. Example <center> <H3>The My Applet</H3> <applet code=“My.class" width=350 height=175> </applet> </center> Rina Zviel-Girshin @ASC

  50. Drawing Shapes • Let's explore some of the methods of the Graphics class that draw shapes in more detail • A shape can be filled or unfilled, depending on which method is invoked • The method parameters specify coordinates and sizes • Java coordinate system has the origin in the upper left corner • Many shapes with curves, like an oval, are drawn by specifying its bounding rectangle • An arc can be thought of as a section of an oval Rina Zviel-Girshin @ASC

More Related