CIS 5930-04 – Spring 2001 - PowerPoint PPT Presentation

cis 5930 04 spring 2001 n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
CIS 5930-04 – Spring 2001 PowerPoint Presentation
Download Presentation
CIS 5930-04 – Spring 2001

play fullscreen
1 / 115
CIS 5930-04 – Spring 2001
94 Views
Download Presentation
leandra-shepard
Download Presentation

CIS 5930-04 – Spring 2001

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. CIS 5930-04 – Spring 2001 Part 3: Introduction to the Java Language: Object-oriented Concepts http://aspen.csit.fsu.edu/it1spring01/ Instructors: Geoffrey Fox , Bryan Carpenter Computational Science and Information Technology Florida State University Acknowledgements: Nancy McCracken Syracuse University dbc@csit.fsu.edu

  2. Java Language Basics dbc@csit.fsu.edu

  3. Obvious similarities to C, C++ • Java syntaxhas many similarities to C, C++. • All variables must be declared • Syntax of expressions and control structures almost identical to C, C++ • C or C++ style comments allowed. dbc@csit.fsu.edu

  4. Obvious differences from C, C++ • No low-level pointers or pointer arithmetic. • Instead have variables and expressions of reference type. • No malloc() or free()—instead have a “new” operator for creating objects, plus automatic garbage collection. • Can declare variables almost anywhere (like C++). • No struct, union, enum, typedef—classes and objects are used uniformly instead. dbc@csit.fsu.edu

  5. Primitive types rationalized • Java characters use 16-bit Unicode Worldwide Character Encoding instead of 8-bit ASCII. Supports all alphabets and languages. • Primitive types for integers and floats have machine independent semantics. • Boolean expressions in Java have value “true” or “false” (not 0, 1, . . .) dbc@csit.fsu.edu

  6. Three kinds of comments in Java • /* ignore all between stars */ • As for C • // ignore all till the end of this line • As for C++ • /** this is a documentation comment */ • Should appear immediately before, eg, class or method definition, and describe intended use. dbc@csit.fsu.edu

  7. Documentation Comments • Used by documentation-generating tools like javadoc to produce documentation, typically in HTML form. • Optionally include formatting tags like @param, which flags a description of a method parameter: /** This method does what it feels like. @param bar This is a pointless argument. */ void foo (int bar) {. . .} • Other formatting tags include @returns which flags a description of a method result value, or @see name, which creates a hypertext link toname. dbc@csit.fsu.edu

  8. Java Keywords • Java reserves the following keywords: • goto is not allowed in Java, but it’s still reserved! • null, true, and false are literals with special meaning. dbc@csit.fsu.edu

  9. Java Language—Program Structure • Source code of a Java program consists of one or more compilation units, each implemented as a file with extension “.java”. • Each compilation unit can contain: • a package statement • import statements • class declarations and/or interface declarations. • In typical Java development environments, exactly one of the class (or interface) declarations in each compilation should be marked public. • The file should be named after the public class. e.g. if the public class isFoo, the file name should be “Foo.java”. dbc@csit.fsu.edu

  10. Java Types • Each Java variable or expression has a definite type, given by a declaration such as int i; double x, y, z; Color c; • There are two sorts of type: • Primitive types like ints or booleans are built into the language. • Reference types.These include class types like Color, and array types (and also interface types). dbc@csit.fsu.edu

  11. Primitive Types • There are 4 integer types: byte short int long Sizes are 8, 16, 32 and 64 bits, respectively. • float is 32 bits, double is 64 bits. Floating point arithmetic and data formats are defined by IEEE 754 standard. • char format is defined by 16 bit Unicode character set. • booleanis eithertrue or false. • One can use casts for arithmetic conversion, as in: int i ; float x ; i = (int) x ; dbc@csit.fsu.edu

  12. Reference Types • These are the types associated with composite entities like objects and arrays. • They are called reference types because a variable or expression in a Java program with reference type represents a reference (or pointer) to a composite entity. • Any variable of reference type may take the value null. • Reference types can be divided into: • Class types • Interface types (discussed later) • Array types dbc@csit.fsu.edu

  13. Strings—an Example of a Class Type • Java environments provide predefined classes for common data types. Every Java environment provides a String class. • Declaration of a String variable looks like: String s ; // variable declaration • The variable declaration itself doesn’t create any objects. We can create a new String object by, e.g.: s = new String(“This is the text”) ; // object creation • These may be combined on one line: String s = new String (“This is the text.”) ; dbc@csit.fsu.edu

  14. A Constructor Function • In the object creation expression: new String (“This is the text.”) the term String (“This is the text.”) is a constructor invocation. • All classes have special “functions” called constructors. These functions have the same name as the class. They initialize the fields of the object. • Constructor functions are only used in object creation operations—nearly always directly after a new operator. • In this example the constructor has one argument: a string literal. • We will see later that in general constructors can have arbitrary argument lists. dbc@csit.fsu.edu

  15. Some features of Strings. • Strings are Java objects, but Java provides some syntax peculiar to strings. • In fact literal string in double quotes itself refers to a pre-existing String object—so in practice we may drop new operation for string constants: String s = “This is the text.” ; • After creation, characters of a string object neverchange. • In other words: string objects are immutable. dbc@csit.fsu.edu

  16. Operations on Strings. • Although a String object is immutable, String-valued variables can be reassigned to refer to new string objects: String str = “Chicken soup with rice” ; int n = str.indexOf( ‘w’ ) ; str = str.substring(0,n) + “is n” + str.substring(n+6) ; // Result: “Chicken soup is nice”. • The operator + is used for concatenation(special syntax for strings). • indexOf() and substring() are methods of the String class—not special syntax! • They illustrate the general syntax of method invocation on an object. dbc@csit.fsu.edu

  17. Array Types • As for objects, declaring an array variable is distinct from creating on the array: int states[] ;// variable declaration and: states = new int[128] ; // array creation • Again, these can be combined: int states[] = new int[128] ; • Alternative (better?) syntax for declaration: int[] states ; dbc@csit.fsu.edu

  18. Subscripts • With states is declared as above: int states[] = new int[128] ; it can be subscripted by integersfrom 0 to 127. • Subscripts are checked at runtime: states[-1] or states[128] will immediately generate exceptions. • Array length is given by the length instance variable: int len = states.length ; // assigns len = 128. dbc@csit.fsu.edu

  19. Arrays of Objects • Arrays of arbitrary objects can be constructed, e.g.: Color manycolors[] = new Color[1024]; • This creates an array of object references. It does not create actual objects for individual elements. • Before you use the array elements, you may need to use object constructors to allocate each object, e.g.: for (int i = 0 ; i < 1024 ; i++) manycolors [i] = new Color() ; dbc@csit.fsu.edu

  20. Multidimensional Arrays • Multidimensional arrays are arrays of arrays. In general these arrays may be “ragged”: int graph[][] = new int[2][]; graph[0] = new int[4]; // Row 0 has length 4 graph[1] = new int[7]; // Row 1 has length 7 . . . graph[1][1] = 9; • Shorthand syntax for creating a rectangular array: char icon[][] = new char [16][16]; // 16 by 16 array • Note icon is still logically an arrays of arrays, and nothing in Java forces it to stay rectangular. E.g. later someone might do: icon [8] = new char [17] ; // Now ragged! dbc@csit.fsu.edu

  21. Java Language—Expressions • Most Java expressions are similar to C. Here are some examples: • arithmetic: 2 + 3 (2 + 3) * i • auto-increment and decrement: i++ // equivalent to i = i +1 • Boolean: ((i > 0) && (j > 0)) || (state == –1) • bit operations: i << 1 // Shift bit pattern 1 place left • conditional expression: (i > 0) ? expression1 : expression2 dbc@csit.fsu.edu

  22. Java Language—More Expressions • Java has some expressions of its own: • string concatenation: “fred” + “jim” // Value is “fredjim” • object “instance of” test: (a instanceof B) //true iff object ahas type (class) B dbc@csit.fsu.edu

  23. Java Control Flow. I: if Statements • Conditional execution of statements: if (some Boolean expression) { statements to be executed if true } • Optional else clause: if (some Boolean expression) { statements to be executed if true } else { statements to be executed if false } • Nested example: if (some Boolean expression) { . . . } else if (another Boolean expression) { . . . } else { . . . } dbc@csit.fsu.edu

  24. Control Flow II: while Loop Constructs • Normal while loop: while (any Boolean) { Stuff to do } Example: int i = 0 ; while(i < a.length) { a [i] = i * i ; i++ ; } • while loop with test at end: do { What to do } while (another Boolean) ; dbc@csit.fsu.edu

  25. Control Flow III: The for Loop Construct • In Java, most often use the C++-like variant: for (declaration1; booleanExpression; expressionList2) { Statements to do } The declaration declaration1 is effected at start of loop, comma-separated expressionList2 is evaluated after every iteration, and the loop terminates when booleanExpression is false. • Typical example: for (int i = 0 ; i < a.length ; i++) a [i] = i * i ; • The original C-like form (no declaration) also available: for (expressionList1 ;booleanExpression;expressionList2) { Statements to do } dbc@csit.fsu.edu

  26. Control Flow IV: The switch Construct • Identical to C: switch (expression) { caseConstant1: // Do following if expression==Constant1 Bunch of Stuff break; caseConstant2: // Do following if expression==Constant2 Bunch of Stuff break; default: // Do the following otherwise Bunch of Stuff break; } dbc@csit.fsu.edu

  27. Control Flow V: break and continue • Unlabeled breakstatement immediately exits the enclosing switch, while, do or forconstruct: while (true) if (++i == a.length || a[i] == v) break ; • Labeled break statement allows to exit an arbitrary enclosing statement, provided it is labeled: assign: { if (i >= a.length) break assign ; a[i] = v ; } (This is not the best way to do this!) • The continue statement skips to the end of the current iteration of the enclosing while, do or for. dbc@csit.fsu.edu

  28. The Java Object Model: Classes, Instances and Methods dbc@csit.fsu.edu

  29. The Java Object Model Overview • Programs are composed of a set of modules called classes. Each class is a template specifying a set of behaviors involving the data of the class. • Each class has variables, or fields,to hold the data, and methods—akin to functions or procedures in other languages—to define the behaviors. • Each object in a program is created as an instance of a class. Each class instance has its own copy of the instance variables defined for the class. • Classes can be used for data encapsulation, hiding the details of the data representation from the user of the class (e.g., by marking variables as private). Instance Variables Methods dbc@csit.fsu.edu

  30. Defining a Class • A class declaration consists of: • a header giving the class name, modifiers, and possible superclass and interface structure. and a class body usually containing: • declarationsof fields (possibly with initializations)—class variables and instance variables. • declarations of methods. • declarations of constructors. These “functions” look like methods, but have the same name as the class. They do initialization when objects—class instances—are created. • nested class and interface definitions. • class or (rarely) instance initialization statements. dbc@csit.fsu.edu

  31. Example: a Predefined Class • A (small) part of the Java Date class: public class Date implements Serializable, Cloneable { public Date( ) {. . .} // Constructor public Date(long msSinceEpoch) {. . .} // Constructor public int getTime( ) {. . .} // Accessor public void setTime(long msSinceEpoch) {. . .} // Mutator public boolean after(Date when) {. . .} // Comparision public boolean equals(Object obj) {. . .} // Comparision . . . } • Note: all variables, methods and constructors visible from “outside” the class—parts of Datethat programmers writing code in other classes are allowed to use—have the publicmodifier in their declaration. dbc@csit.fsu.edu

  32. Creating a Class Instance • The Date class represents a particular date and time, with a resolution of milliseconds. • The first of the two Date constructors (“no-argument constructor”) constructs an instance of the Date class and sets its value to the current moment: new Date() • Constructors (like methods) can be overloaded. Constructors of same name are distinct if they have distinct argument types. If ms is a long, the object: new Date(ms) represents a moment ms milliseconds after January 1, 1970, 00:00:00 UTC (Coordinated Universal Time). • Java will become obsolete (2^63 – 1) / 1000 seconds after that (approximately 292 million years AD, UTC). . . dbc@csit.fsu.edu

  33. Using a Class • An example application using a method of the Dateclass: import java.util.Date; public class DateTest { public static void main (String[ ] args) { Date early = new Date(1000) ; // very early seventies! Date today = new Date() ; // Now! if (today.after(early)) System.out.println( "Today is not early!") ; } } dbc@csit.fsu.edu

  34. Instance Variables • A very simple class: public class Complex { public double real ; public double imaginary ; } • Essentially like a C struct. Every instance of Complex has its own real and imaginary variables. These fields are therefore called instance variables. • Use: Complex z = new Complex() ; // Default constructor z.real = 0.0 ; z.imaginary = 1.0 ; dbc@csit.fsu.edu

  35. Class Variables • Besides instance variables, a class may contain “global variables” that are not associated with any instance. • A class variable (also called a static variable) is flagged by the staticmodifier in its declaration: class Potato { public String name; static public int num = 0 ; // Class variable—number of potatoes. } Potato p = new Potato(), q = new Potato() ; p.name = “one potato” ; q.name = “two potato” ; Potato.num += 2 ; // static field prefix is class name. dbc@csit.fsu.edu

  36. Method Definitions • Subprograms in Java are called methods. In the abstract, the declaration format is: methodModifiers returnType methodName(parameter list) { declarations and statements } • The parameter list contains the types and names of all the parameters. • The declarations and statements are the body of the method. Parameter names, and variables declared in the body, are local to it. • Control returns from a method when the body finishes execution or a return statement is executed. return statements may return a result value. • Parameters are passed by value. dbc@csit.fsu.edu

  37. Local variables • Formal parameters of methods, and variables declared inside the bodies methods, are local variables. • These are a third kind of variable in Java: they are neither instance variables or class variables. dbc@csit.fsu.edu

  38. Static and Non-static Methods • Like fields, methods come in two varieties, which are properly called instance methods and class methods. • The terms non-static methods and static methods are also commonly used. • In all Java applications illustrated so far, the main() method had the modifier static—the main method of an application is required to be a static method. • All other examples of methods illustrated so far were instance methods. dbc@csit.fsu.edu

  39. Instance Methods • Instance methods operate in the context of a particular class instance (i.e. a particular object). • The instance variables of the current object can be accessed without any prefix: public class Complex { //Addsz to the current object public void add(Complex z) { real += z.real ; imaginary += z.imaginary ; } public double real ; public double imaginary ; } dbc@csit.fsu.edu

  40. Invoking an Instance method • This example initializes a and b, then increments the value of a by amount b: Complex a = new Complex(), b = new Complex() ; a.real = 0.707 ; a.imaginary = -0.707 ; b.real = -1.0 ; b.imaginary = 0.0 ; a.add(b) ; // Method invocation dbc@csit.fsu.edu

  41. this • Within an instance method or constructor the keyword thisrefers to the current instance. • i.e. the object on which the method was invoked, or which the constructor is initializing. • Appropriate usage—passing self-reference to some other method: public class Complex { . . . Definition of add(), etc. public void addTo(Complex accumulator) { accumulator.add(this) ; } } • The invocation a.addTo(b) adds the value of a to b, i.e. it is equivalent to b.add(a). dbc@csit.fsu.edu

  42. this as a prefix • Some programmers will write the this prefix explicitly on every access to an instance variable, e.g.: public void negate() { this.real = – this.real ; this.imaginary = – this.imaginary ; } • This is legal, but ugly! • One time you must use this as a prefix to an instance variable is when the field is hidden by declaration of a local variable with the same name. • The only common example is in constructor declarations. A constructor parameter whose value is used to initialize a field is conventionally given the same name as the field it initializes. See examples later. dbc@csit.fsu.edu

  43. Static Methods • A static method does not operate in the context of a particular instance. • Instance variables of the class cannot be accessed inside the body of a static method unless an explicit object prefix is given. • The keyword thiscannot be used in the body of a static method. • To invoke a static method it should be prefixed by the name of the class (similar rule to accessing class variables). • This prefix can be omitted if the method is invoked from another method, etc, defined in the same class. dbc@csit.fsu.edu

  44. Constructors • Constructors are “functions” (not, strictly speaking, methods) that have the same name as the class they belong to. • Any number of constructors can be defined for a class, provided they can be distinguished by the number and type of their parameters (overloading). • If no constructors are explicitly defined, the compiler generates a single default constructor with no arguments. • Note: the default constructor disappears once any explicitly-defined constructor is given! dbc@csit.fsu.edu

  45. A Better Potato class Potato { public Potato(String name) { this.name = name ; // Idiomatic use of this num++ ; } public static int getNum() { // A static method return num ; } private String name ; // Note: now private private static int num = 0 ; // Also private } Potato p = new Potato(“one potato”), q = new Potato(“two potato”) ; System.out.println(“There are ” + Potato.getNum() + “ potatoes”) ; dbc@csit.fsu.edu

  46. Remarks • In the constructor, the unqualified symbol name refers to the local variable declared in the parameter list. • Because this declaration hides the declaration of name as an instance variable, we must prefix with this to access the latter. • The data fields are now private. This means they can be accessed only from methods within the class, not from other classes. • The method getNum() returns a “global” property of the class—the total number of Potato objects that have been created. • Hence it is natural to declare it as a static method—it is not associated with any individual instance. dbc@csit.fsu.edu

  47. Type Conversions • Java allows implicit type conversions in some contexts. • Generally speaking the conversions allowed implicitly (without a cast) are what are called widening conversions. • For primitive types, the widening conversions are from any integer type to anywider integer type, (int to long, etc) or from a floatto adouble. • Narrowing conversions, by contrast, would include conversion from long to int, or from a floating point type to an integer type. • Narrowing conversions usually have to be specified explicitly with a cast, e.g. float x ; int i = (int) x ; dbc@csit.fsu.edu

  48. Overloading • A class can declare several methods with the same name, providing each declaration has a different number of arguments, or different argument types. • We refer to the combination of the method name and its list of argument types as the signature of the method. • Example: class Shape { setColor(Color c) { . . .} setColor(int rgb) { . . .} setColor(int r, int g, int b) { . . .} . . . } • The method setColor() is overloaded with three different signatures. dbc@csit.fsu.edu

  49. Calling an Overloaded Method • If the types of the argument expressions in a method invocationexactly match the types of the parameters in one particular declaration of the method, the compiler naturally chooses to call that particular method implementation. • There is a complication, though: the Java language allows implicit type conversion of method arguments. • The allowed conversions are the widening conversions. • In general overload resolution chooses the most specific method signature matching the actual arguments. • If there are several applicable signatures, and no single one is more specific than all the others, a compile time error is flagged. dbc@csit.fsu.edu

  50. Examples of overload resolution void foo(long p) {. . .} // Signature I void foo(int p) {. . .} // Signature II void foo(long p, int q) {. . .} // Signature III void foo(int p, long q) {. . .} // Signature IV long l ; short s ; int i ; foo(l) ; // Exact match—use Signature I. foo(s) ; // Do widening conversion of s to int, and use // Signature II—unique “most specific” case. foo(l, s) ; // Uses Signature III—only case applicable by // widening conversions. foo(i, i) ; // Compile time error! Signatures III and IV // are both applicable but neither is more specific // than the other! dbc@csit.fsu.edu