Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS445 - Object Oriented Design and Programming  Java.

Similar presentations


Presentation on theme: "CS445 - Object Oriented Design and Programming  Java."— Presentation transcript:

1 CS445 - Object Oriented Design and Programming  Java

2 CS445 - Object Oriented Design and Programming Topics  Class Basics and Benefits  Creating Objects Using Constructors  Calling Methods  Using Object References  Calling Static Methods and Using Static Class Variables  Using Predefined Java Classes

3 CS445 - Object Oriented Design and Programming Object-Oriented Programming  Classes combine data and the methods (code) to manipulate the data  Classes are a template used to create specific objects  All Java programs consist of at least one class.  Two types of classes –Application/Applet classes –Service classes

4 CS445 - Object Oriented Design and Programming Example  Student class –Data: name, year, and grade point average –Methods: store/get the value of each piece of data, promote to next year, etc.  Student Object: student1 –Data: Maria Gonzales, Sophomore, 3.5

5 CS445 - Object Oriented Design and Programming Some Terminology  Object reference: identifier of the object  Instantiating an object: creating an object of a class  Instance of the class: the object  Methods: the code to manipulate the object data  Calling a method: invoking a service for an object.

6 CS445 - Object Oriented Design and Programming Class Data  Instance variables: variables defined in the class and given values in the object  Fields: instance variables and static variables (we'll define static later)  Members of a class: the class's fields and methods  Fields can be: –any primitive data type (int, double, etc.) –objects

7 CS445 - Object Oriented Design and Programming Encapsulation  Instance variables are usually declared to be private, which means users of the class must reference the data of an object by calling methods of the class.  Thus the methods provide a protective shell around the data. We call this encapsulation.  Benefit: the class methods can ensure that the object data is always valid.

8 CS445 - Object Oriented Design and Programming Naming Conventions  Class names: start with a capital letter  Object references: start with a lowercase letter  In both cases, internal words start with a capital letter  Example: class: Student objects: student1, student2

9 CS445 - Object Oriented Design and Programming Declare an Object Reference Syntax: ClassName objectReference; or ClassName objectRef1, objectRef2…;  Object reference holds address of object  Example: Date d1;

10 CS445 - Object Oriented Design and Programming Instantiate an Object  Objects MUST be instantiated before they can be used  Call a constructor using new keyword  Constructor has same name as class.  Syntax: objectReference = new ClassName( arg list );  Arg list (argument list) is comma-separated list of initial values to assign to object data

11 CS445 - Object Oriented Design and Programming The Argument List in an API  Pairs of dataType variableName  Specify –Order of arguments –Data type of each argument  Arguments can be: –Any expression that evaluates to the specified data type

12 CS445 - Object Oriented Design and Programming Void Methods  Void method Does not return a value System.out.print(“Hello”); System.out.println(“Good bye”); name.setName(“CS”, “201”); object method arguments

13 CS445 - Object Oriented Design and Programming Value-Returning Methods  Value-returning method Returns a value to the calling program String first; String last; Name name; System.out.print(“Enter first name: “); first = inData.readLine(); System.out.print(“Enter last name: “); last = inData.readLine(); name.setName(first, last);

14 CS445 - Object Oriented Design and Programming Value-returning example public String firstLastFormat() { return first + “ “ + last; } System.out.print(name.firstLastFormat()); object method Argument to print method is string returned from firstLastFormat method

15 CS445 - Object Oriented Design and Programming Method Return Values  Can be a primitive data type, class type, or void  A value-returning method –Return value is not void –The method call is used in an expression. When the expression is evaluated, the return value of the method replaces the method call.  Methods with a void return type –Have no value –Method call is complete statement (ends with ;)

16 CS445 - Object Oriented Design and Programming Dot Notation  Use when calling method to specify which object's data to use in the method  Syntax: objectReference.methodName( arg1, arg2, … ) Note: no data types in method call; values only! Example Next Slide

17 CS445 - Object Oriented Design and Programming Example Methods.java public class Methods { public static void main( String [] args ) { Date independenceDay = new Date( 7, 4, 1776 ); int independenceMonth = independenceDay.getMonth( ); System.out.println( "Independence day is in month " + independenceMonth ); Date graduationDate = new Date( 5, 15, 2008 ); System.out.println( "The current day for graduation is " + graduationDate.getDay( ) ); graduationDate.setDay( 12 ); System.out.println( "The revised day for graduation is " + graduationDate.getDay( ) ); }

18 CS445 - Object Oriented Design and Programming Object Reference vs. Object Data  Object references point to the location of object data.  An object can have multiple object references pointing to it.  Or an object can have no object references pointing to it. If so, the garbage collector will free the object's memory  See Example Next Slide

19 CS445 - Object Oriented Design and Programming Example ObjectReferenceAssignment.java public class ObjectReferenceAssignment { public static void main( String [] args ) { Date hireDate = new Date( 2, 15, 2003 ); System.out.println( "hireDate is " + hireDate.getMonth( ) + "/" + hireDate.getDay( ) + "/" + hireDate.getYear( ) ); Date promotionDate = new Date( 9, 28, 2004 ); System.out.println( "promotionDate is " + promotionDate.getMonth( ) + "/" + promotionDate.getDay( ) + "/" + promotionDate.getYear( ) ); promotionDate = hireDate;  System.out.println( "\nAfter assigning hireDate “ + "to promotionDate:" ); System.out.println( "hireDate is " + hireDate.getMonth( ) + "/" + hireDate.getDay( ) + "/" + hireDate.getYear( ) ); System.out.println( "promotionDate is " + promotionDate.getMonth( ) + "/" + promotionDate.getDay( ) + "/" + promotionDate.getYear( ) ); }

20 CS445 - Object Oriented Design and Programming Two References to an Object  After the example runs, two object references point to the same object

21 CS445 - Object Oriented Design and Programming null Object References  An object reference can point to no object. In that case, the object reference has the value null  Object references have the value null when they have been declared, but have not been used to instantiate an object.  Attempting to use a null object reference causes a NullPointerException at run time.

22 CS445 - Object Oriented Design and Programming Example NullReference.java public class NullReference { public static void main( String[] args ) { Date aDate; aDate.setMonth( 5 ); }

23 CS445 - Object Oriented Design and Programming Example NullReference2.java public class NullReference2 { public static void main( String[] args ) { Date independenceDay = new Date( 7, 4, 1776 ); System.out.println( "The month of independenceDay is “ + independenceDay.getMonth( ) ); independenceDay = null; // attempt to use object reference System.out.println( "The month of independenceDay is “ + independenceDay.getMonth( ) ); } }

24 CS445 - Object Oriented Design and Programming Date.java Class import java.awt.Graphics; public class Date { private int month; private int day; private int year; public Date( ) { setDate( 1, 1, 2000 ); } public Date( int mm, int dd, int yyyy ) { setDate( mm, dd, yyyy ); } /* accessor methods */ int getMonth( ) { return month; } int getDay( ) { return day; } int getYear( ) { return year; } /** mutator method */ public void setMonth( int mm ) { month = ( mm >= 1 && mm <= 12 ? mm : 1 ); }

25 CS445 - Object Oriented Design and Programming Date.java Class public void setDay( int dd ) { int [] validDays = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; day = ( dd >= 1 && dd <= validDays[month] ? dd : 1 ); } public void setYear( int yyyy ) { year = yyyy; } public void setDate( int mm, int dd, int yyyy ) { setMonth( mm ); setDay( dd ); setYear(yyyy); } public String toString( ) { return month + "/" + day + "/" + year; } public boolean equals( Date d ) { if ( month == d.month && day == d.day && year == d.year ) return true; else return false; } Comparing Objects Converting an Object to String

26 CS445 - Object Oriented Design and Programming static Methods  Also called class methods  Can be called without instantiating an object  Might provide some quick, one-time functionality, for example, popping up a dialog box  In method API, keyword static precedes return type static dataType mthodName (arg1,ard2,…);

27 CS445 - Object Oriented Design and Programming Calling static Methods  Use dot syntax with class name instead of object reference  Syntax: ClassName.methodName( args )  Example: int absValue = Math.abs( -9 );  Uses of class methods –Provide access to class variables without using an object

28 CS445 - Object Oriented Design and Programming static Class Variables  Syntax: ClassName.staticVariable  Example: Color.BLUE BLUE is a static constant of the Color class.

29 CS445 - Object Oriented Design and Programming Static Class Variables and Static Methods class Counter { private int value; private static int numCounters = 0;  public Counter() { value = 0; numCounters++; } public static int getNumCounters() {  return numCounters; } }... System.out.println("Number of counters: " + Counter.getNumCounters()); 

30 CS445 - Object Oriented Design and Programming  Class (static) vs. instance variables –Instance variable: each instance has its own copy –Class variable: the class has one copy for all instances  Can use instance variables –In instance methods only  Can use class variables –In instance methods –In class methods

31 CS445 - Object Oriented Design and Programming Topics  Defining a Class  Defining Instance Variables  Writing Methods  The Object Reference this  The toString and equals Methods  static Members of a Class  Creating Packages

32 CS445 - Object Oriented Design and Programming Why User-Defined Classes? Primitive data types (int, double, char,.. ) are great … … but in the real world, we deal with more complex objects: products, Web sites, flight records, employees, students,.. Object-oriented programming enables us to manipulate real-world objects.

33 CS445 - Object Oriented Design and Programming User-Defined Classes  Combine data and the methods that operate on the data  Advantages: –Class is responsible for the validity of the data. –Implementation details can be hidden. –Class can be reused.  Client of a class –A program that instantiates objects and calls methods of the class

34 CS445 - Object Oriented Design and Programming Syntax for Defining a Class accessModifier class ClassName { // class definition goes here }

35 CS445 - Object Oriented Design and Programming Software Engineering Tip  Use a noun for the class name.  Begin the class name with a capital letter.

36 CS445 - Object Oriented Design and Programming Important Terminology  Fields –instance variables: data for each object –class data: static data that all objects share  Members –fields and methods  Access Modifier –determines access rights for the class and its members –defines where the class and its members can be used

37 CS445 - Object Oriented Design and Programming Access Modifiers Access ModifierClass or member can be referenced by… publicmethods of the same class, and methods of other classes privatemethods of the same class only protectedmethods of the same class, methods of subclasses, and methods of classes in the same package No access modifier (package access) methods in the same package only

38 CS445 - Object Oriented Design and Programming public vs. private  Classes are usually declared to be public  Instance variables are usually declared to be private  Methods that will be called by the client of the class are usually declared to be public  Methods that will be called only by other methods of the class are usually declared to be private  APIs of methods are published (made known) so that clients will know how to instantiate objects and call the methods of the class

39 CS445 - Object Oriented Design and Programming Defining Instance Variables Syntax: accessModifier dataType identifierList; dataType can be primitive date type or a class type identifierList can contain: –one or more variable names of the same data type –multiple variable names separated by commas –initial values  Optionally, instance variables can be declared as final

40 CS445 - Object Oriented Design and Programming Examples of Instance Variable Definitions private String name = ""; private final int PERFECT_SCORE = 100, PASSING_SCORE = 60; private int startX, startY, width, height;

41 CS445 - Object Oriented Design and Programming Software Engineering Tips  Define instance variables for the data that all objects will have in common.  Define instance variables as private so that only the methods of the class will be able to set or change their values.  Begin the identifier name with a lowercase letter and capitalize internal words.

42 CS445 - Object Oriented Design and Programming The Auto Class public class Auto { private String model; private int milesDriven; private double gallonsOfGas; }

43 CS445 - Object Oriented Design and Programming Writing Methods Syntax: accessModifier returnType methodName( parameter list ) // method header { // method body }  parameter list is a comma-separated list of data types and variable names. –To the client, these are arguments –To the method, these are parameters  Note that the method header is the method API.

44 CS445 - Object Oriented Design and Programming Software Engineering Tips  Use verbs for method names.  Begin the method name with a lowercase letter and capitalize internal words.

45 CS445 - Object Oriented Design and Programming Method Return Types  The return type of a method is the data type of the value that the method returns to the caller. The return type can be any of Java's primitive data types, any class type, or void.  Methods with a return type of void do not return a value to the caller.

46 CS445 - Object Oriented Design and Programming Method Body  The code that performs the method's function is written between the beginning and ending curly braces.  Unlike if statements and loops, these curly braces are required, regardless of the number of statements in the method body.  In the method body, a method can declare variables, call other methods, and use any of the program structures we've discussed, such as if/else statements, while loops, for loops, switch statements, and do/while loops.

47 CS445 - Object Oriented Design and Programming main is a Method public static void main( String [] args ) { // application code } Let's look at main's API in detail: public main can be called from outside the class. (The JVM calls main.) static main can be called by the JVM without instantiating an object. void main does not return a value String [] args main's parameter is a String array

48 CS445 - Object Oriented Design and Programming Value-Returning Methods  Use a return statement to return the value  Syntax: return expression;

49 CS445 - Object Oriented Design and Programming Constructors  Special methods that are called when an object is instantiated using the new keyword.  A class can have several constructors.  The job of the class constructors is to initialize the instance variables of the new object.

50 CS445 - Object Oriented Design and Programming Defining a Constructor Syntax: public ClassName( parameter list ) { // constructor body } Note: no return value, not even void!  Each constructor must have a different number of parameters or parameters of different types  Default constructor: a constructor that takes no arguments.  See Examples 7.1 and 7.2, Auto.java and AutoClient.java

51 CS445 - Object Oriented Design and Programming Default Initial Values  If the constructor does not assign values to the instance variables, they are auto-assigned default values depending on the instance variable data type. Data TypeDefault Value byte, short, int, long0 float, double0.0 charspace booleanfalse Any object reference (for example, a String) null

52 CS445 - Object Oriented Design and Programming Common Error Trap Do not specify a return value for a constructor (not even void). Doing so will cause a compiler error in the client program when the client attempts to instantiate an object of the class.

53 CS445 - Object Oriented Design and Programming Class Scope  Instance variables have class scope –Any constructor or method of a class can directly refer to instance variables.  Methods also have class scope –Any method or constructor of a class can call any other method of a class (without using an object reference).

54 CS445 - Object Oriented Design and Programming Local Scope  A method's parameters have local scope, meaning that: –a method can directly access its parameters. –a method's parameters cannot be accessed by other methods.  A method can define local variables which also have local scope, meaning that: –a method can access its local variables. –a method's local variables cannot be accessed by other methods.

55 CS445 - Object Oriented Design and Programming Summary of Scope  A method in a class can access: –the instance variables of its class –any parameters sent to the method –any variable the method declares from the point of declaration until the end of the method or until the end of the block in which the variable is declared, whichever comes first –any methods in the class

56 CS445 - Object Oriented Design and Programming Using Java Predefined Classes  Java Packages  The String Class  Using System.out  The Math Class  The Wrapper Classes  Dialog Boxes  Console Input Using the Scanner Class

57 CS445 - Object Oriented Design and Programming Java Predefined Classes  Included in the Java SDK are more than 2,000 classes that can be used to add functionality to our programs  APIs for Java classes are published on Sun Microsystems Web site: http://www.java.sun.com

58 CS445 - Object Oriented Design and Programming Java Packages  Classes are grouped in packages according to functionality PackageCategories of Classes java.langBasic functionality common to many programs, such as the String class and Math class java.awtGraphics classes for drawing and using colors javax.swingUser-interface components java.textClasses for formatting numeric output java.utilThe Scanner class and other miscellaneous classes

59 CS445 - Object Oriented Design and Programming Using a Class From a Package  Classes in java.lang are automatically available to use  Classes in other packages need to be "imported" using this syntax: import package.ClassName; or import package.*;  Example import java.text.DecimalFormat; or import java.text.*;

60 CS445 - Object Oriented Design and Programming The String Class  Represents a sequence of characters  String constructors: String( String str ) allocates a String object with the value of str, which can be String object or a String literal String( ) allocates an empty String

61 CS445 - Object Oriented Design and Programming String Concatenation Operators + appends a String to another String. At least one operand must be a String += shortcut String concatenation operator

62 CS445 - Object Oriented Design and Programming The length Method  Example: String hello = "Hello"; int len = hello.length( ); The value of len is 5 Return type Method name and argument list intlength( ) returns the number of characters in the String

63 CS445 - Object Oriented Design and Programming The toUpperCase and toLowercase Methods  Example: String hello = "Hello"; hello = hello.toUpperCase( ); The value of hello is "HELLO" Return type Method name and argument list String toU p perCase( ) returns a copy of the String will all letters uppercase StringtoLowerCase( ) returns a copy of the String will all letters lowercase

64 CS445 - Object Oriented Design and Programming The indexOf Methods The index of the first character of a String is 0.  Example: String hello = "Hello"; int index = hello.indexOf( 'e' ); The value of index is 1. Return type Method name and argument list intindexOf( String searchString ) returns the index of the first character of searchString or -1 if not found intindexOf( char searchChar ) returns the index of the first character of searchChar or -1 if not found

65 CS445 - Object Oriented Design and Programming The substring Method  Example: String hello = "Hello"; String lo = hello.substring( 3, hello.length( )-1 ); The value of lo is 'lo' Return type Method name and argument list Stringsubstring( int startIndex, int endIndex ) returns a substring of the String object beginning at the character at index startIndex and ending at the character at index ( endIndex – 1 )

66 CS445 - Object Oriented Design and Programming  Specifying a negative start index or a start index past the last character of the String will generate a StringIndexOutOfBoundsException.  Specifying a negative end index or an end index greater than the length of the String will also generate a StringIndexOutOfBoundsException

67 CS445 - Object Oriented Design and Programming System.out  System is a class in java.lang package  out is a a static constant field, which is an object of class PrintStream.  PrintStream is a class in java.io package  Since out is static we can refer to it using the class name System.out  PrintStream Class has 2 methods for printing, print and println that accept any argument type and print to the standard java console.

68 CS445 - Object Oriented Design and Programming Using System.out Example: System.out.print( "The answer is " ); System.out.println( 3 ); output is: The answer is 3 Return type Method name and argument list voidprint( anyDataType argument ) prints argument to the standard output device (by default, the Java console) voidprintln( anyDataType argument ) prints argument to the standard output device (Java console) followed by a newline character

69 CS445 - Object Oriented Design and Programming The toString Method  All classes have a toString method which converts an object to string for printing Return type Method name and argument list StringtoString( ) converts the object data to a String for printing

70 CS445 - Object Oriented Design and Programming The Math Class Constants  Two static constants PI - the value of pi E - the base of the natural logarithm  Example: System.out.println( Math.PI ); System.out.println( Math.E ); output is: 3.141592653589793 2.718281828459045

71 CS445 - Object Oriented Design and Programming Methods of the Math Class Return typeMethod name and argument list dataTypeOfArgabs( dataType arg ) returns the absolute value of the argument arg, which can be a double, float, int or long. doublelog( double a ) returns the natural logarithm (in base e) of its argument. doublesqrt( double a ) returns the positive square root of a doublepow( double base, double exp ) returns the value of base raised to the power of exp

72 CS445 - Object Oriented Design and Programming The Math round Method  Rounding rules: –Any factional part <.5 is rounded down –Any fractional part.5 and above is rounded up Return type Method name and argument list longround( double a ) returns the closest integer to its argument a

73 CS445 - Object Oriented Design and Programming The Math min/max Methods  Find smallest of three numbers: int smaller = Math.min( num1, num2 ); int smallest = Math.min( smaller, num3 ); Return typeMethod name and argument list dataTypeOfArgsmin( dataType a, dataType b ) returns the smaller of the two arguments. The arguments can be doubles, floats, ints, or longs. dataTypeOfArgsmax( dataType a, dataType b ) returns the larger of the two arguments. The arguments can be doubles, floats, ints, or longs.

74 CS445 - Object Oriented Design and Programming The Math random Method  Generates a pseudorandom number (appearing to be random, but mathematically calculated)  To generate a random integer between a and up to, but not including, b: int randNum = a + (int)( Math.random( ) * ( b - a ) ); Return type Method name and argument list doublerandom( ) returns a random number greater than or equal to 0 and less than 1

75 CS445 - Object Oriented Design and Programming The Wrapper Classes  "wraps" the value of a primitive data type into an object  Useful when methods require an object argument  Also useful for converting Strings to an int or double

76 CS445 - Object Oriented Design and Programming Wrapper Classes Primitive Data TypeWrapper Class doubleDouble floatFloat longLong intInteger shortShort byteByte charCharacter booleanBoolean

77 CS445 - Object Oriented Design and Programming Autoboxing and Unboxing  Autoboxing: –Automatic conversion between a primitive type and a wrapper object when a primitive type is used where an object is expected Integer intObject = 42;  Unboxing –Automatic conversion between a wrapper object and a primitive data type when a wrapper object is used where a primitive data type is expected int fortyTwo = intObject;

78 CS445 - Object Oriented Design and Programming Integer and Double Methods  static Integer Methods  static Double Methods See Example 3.15 DemoWrapper.java Return valueMethod Name and argument list intparseInt( String s ) returns the String s as an int IntegervalueOf( String s ) returns the String s as an Integer object Return valueMethod Name and argument list doubleparseDouble( String s ) returns the String s as a double DoublevalueOf( String s ) returns the String s as a Double object


Download ppt "CS445 - Object Oriented Design and Programming  Java."

Similar presentations


Ads by Google