1 / 78

Chapter 3

Chapter 3. Introduction to Object-Oriented Programming: Using Classes. 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.

kaia
Télécharger la présentation

Chapter 3

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.

E N D

Presentation Transcript


  1. Chapter 3 Introduction to Object-Oriented Programming: Using Classes

  2. 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. 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. Why Use Classes? • Usually, the data for a program is not simply one item. • Often we need to manage entities like students, books, flights, etc. • We need to be able to manipulate such entities as a unit. • Classes allow us to separate the data for each object, while using common code to manipulate each object.

  5. Example • Student class • Data: name, year, and grade point average • Methods: store/get the value of the data, promote to next year, etc. • Student object Object name: student1 Data: Maria Gonzales, Sophomore, 3.5

  6. Objects • Object reference • an identifier of the object • Instantiating an object • creating an object of a class; assigns initial values to the object data. • Objects need to be instantiated before being used • Instance of the class • an object after instantiation

  7. Class Members • Members of a class • the class' fields and methods • Fields • instance variables and static variables (we'll define static later) • Instance variables • variables defined in the class and given a value in each object fields can be: • any primitive data type (int, double, etc.) • objects of the same or another class • Methods • the code to manipulate the object data

  8. Encapsulation • Instance variables are usually declared to be private, which means that they cannot be accessed directly outside the class. • Users (clients) of the class can only reference the private 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.

  9. 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: classes: Student, PetAnimal objects: marcusAustin, myBoaConstrictor

  10. Reusability • Reuse • class code is already written and tested • new applications can be built faster • the applications will be more reliable Example: A Date class could be used in a calendar program, appointment-scheduling program, online shopping program, etc.

  11. How to Reuse a Class • You don't need to know how the class is written or see the code of the class • You do need to know the application programming interface (API) of the class. • The API is published and tells you: • how to create objects • what methods are available • how to call the methods

  12. 1. Declare an Object Reference • An object reference holds the address of the object • Syntax to declare an object reference: ClassName objectReference; or ClassName objectRef1, objectRef2…; • Example: SimpleDate d1;

  13. 2. Instantiate an Object • Objects must be instantiated before they can be used • Call a constructor using the new keyword • constructor: a special method that creates an object and assigns initial values to data • Constructor has the same name as the class. • Syntax: objectReference = new ClassName( arg list ); • Arg list (argument list) is comma-separated list of initial values to assign to the object data

  14. SimpleDate Class API

  15. Instantiation Examples SimpleDate independenceDay; independenceDay = new SimpleDate( 7, 4, 1776 ); SimpleDate graduationDate = new SimpleDate( 5, 15, 2012 ); SimpleDate defaultDate = new SimpleDate( ); See Example 3.1 Constructors.java

  16. Objects After Instantiation

  17. Calling a Method

  18. Method Classifications • Accessormethods • “get” methods • return the current values of object data • Mutatormethods • “set” methods • change the values of object data

  19. SimpleDate Accessor Methods

  20. SimpleDate Mutator Methods

  21. Date Donut setYear (int yy) Date ( ) setDay (int dd) Date (int mm, int dd, int yy) private data setMonth (int mm) int getMonth( ) int getYear( ) int getDay( )

  22. Dot Notation Use when calling a method, you need to specify which object's data the method should use. Syntax: objectReference.methodName( arg1, arg2, … )

  23. Method Return Values • Can be a primitive data type, class type, or void • A value-returning method • The method returns a value. • Thus 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 ;)

  24. The Argument List in an API • Comma-separated pairs of dataType variableName • The argument list specifies: • The order of the arguments • The data type of each argument • Arguments can be: • Any expression that evaluates to the specified data type

  25. Reading an API: Value-returning Method int getMonth( ) return value method name is the method takes is an int getMonth no arguments Example method calls (assuming d1 is a SimpleDate object): int m = d1.getMonth( ); or System.out.println( d1.getMonth( ) );

  26. Reading an API: void Method void setMonth( int newMonth ) method does method name is the method takes one not return setMonth argument: an int a value Example method call (assuming d1 is a SimpleDate object): d1.setMonth( 12 ); See Example 3.2 Methods.java

  27. Common Error Trap When calling a method, include only expressions in your argument list. Including data types in your argument list will cause a compiler error. If the method takes no arguments, remember to include the empty parentheses after the method's name. The parentheses are required even if there are no arguments.

  28. Object Reference vs. Object Data • Object references point to the memory 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 collectorwill free the object's memory See Example 3.3 ObjectReferenceAssignment.java

  29. Two References to an Object After Example 3.3 runs, two object references point to the same object

  30. 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. See Example 3.4 NullReference.java and Example 3.5 NullReference2.java

  31. Using Java Predefined Classes • Java Packages • The String Class • Formatting Output using DecimalFormat • The Random class • Console Input Using the Scanner Class • Using static methods and data • Using System andthe PrintStream class • The Math Class • Formatting Output using NumberFormat • The Wrapper Classes • Dialog Boxes

  32. Java Predefined Classes • The Java SDK provides more than 2,000 classes that can be used to add functionality to our programs • APIs for Java classes are published on Oracle’s website: www.oracle.com/technetwork/java/ • Also see Appendix F

  33. Java Packages Classes are grouped in packages according to functionality.

  34. Using a Class From a Package • Classes in java.lang are automatically available. • Classes in other packages need to be "imported" using this syntax: import package.ClassName; or import package.*; (imports all required classes from package) • Example import java.text.DecimalFormat; or import java.text.*;

  35. The String Class Represents a sequence of characters Examples: String greeting = new String( "Hello" ); String empty = new String( );

  36. String Concatenation Operators + appends a String to another String. At least one operand must be a String. += String concatenation operator Example: String s1 = new String( "Hello " ); String s2 = "there. "; String s3 = s1 + s2; // s3 is: // Hello there String s3 += "!"; // s3 is now: // Hello there!

  37. The length Method Example String greeting = "Hello"; int len = greeting.length( ); The value of len is 5

  38. toUpperCase and toLowerCase Methods Example: String greeting = "Hello"; greeting = greeting.toUpperCase( ); The value of greeting is "HELLO"

  39. The indexOf Methods The index of the first character of a String is 0. Example: String greeting = "Hello"; int index = greeting.indexOf( 'e' ); The value of index is 1.

  40. The charAt Method Example String greeting = "Hello"; char firstChar = greeting.charAt( 0 ); The value of firstChar is 'H'

  41. The substring Method Example: String greeting = "Hello"; String endOfHello = greeting.substring( 3, hello.length( ) ); The value of endOfHello is “lo” See Example 3.6 StringDemo.java

  42. Example 3.6 StringDemo.java String s1 = new String( "OOP in Java " ); System.out.println( "s1 is: " + s1 ); String s2 = "is not that difficult. "; System.out.println( "s2 is: " + s2 ); String s3 = s1 + s2; // new String is s1, followed by s2 System.out.println( "s1 + s2 returns: " + s3 ); System.out.println( "s1 is still: " + s1 ); // s1 is unchanged System.out.println( "s2 is still: " + s2 ); // s2 is unchanged String greeting1 = "Hi"; // instantiate greeting1 System.out.println( "\nThe length of " + greeting1 + " is “ + greeting1.length( ) ); String greeting2 = new String( "Hello" ); // instantiate greeting2 int len = greeting2.length( ); // len will be assigned 5 System.out.println( "The length of " + greeting2 + " is " + len );

  43. Example 3.6 StringDemo.java String empty = new String( ); System.out.println( "The length of the empty String is “ + empty.length( ) ); String greeting2Upper = greeting2.toUpperCase( ); System.out.println( ); System.out.println( greeting2 + " converted to upper case is “ + greeting2Upper ); String invertedName = "Lincoln, Abraham"; int comma = invertedName.indexOf( ',' ); // find the comma System.out.println( "\nThe index of " + ',' + " in “ + invertedName + " is " + comma ); // extract all characters up to comma String lastName = invertedName.substring( 0, comma ); System.out.println( "Dear Mr. " + lastName );

  44. Common Error Trap 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 also will generate aStringIndexOutOfBoundsException

  45. Formatting Numeric Output The DecimalFormat class and the NumberFormat class allow you to specify the number of digits for printing and to add dollar signs and percent signs to your output, • Both classes are in the java.text package. • We will cover the NumberFormat class later.

  46. The DecimalFormat Class Pattern characters: 0 required digit, include if 0 # optional digit, suppress if 0 . decimal point , comma separator % multiply by 100 and display a percent sign

  47. The DecimalFormatformat Method To format a numeric value for output, call the format method. See Example 3.7 DemoDecimalFormat.java

  48. import java.text.DecimalFormat; public class DemoDecimalFormat { public static void main( String [] args ) { // first, instantiate a DecimalFormat object specifying a pattern for currency DecimalFormat pricePattern = new DecimalFormat( "$##0.00" ); double price1 = 78.66666666; double price2 = 34.5; double price3 = .3333333; int price4 = 3; double price5 = 100.23; // then print the values using the pattern System.out.println( "The first price is: “ + pricePattern.format( price1 ) ); System.out.println( "\nThe second price is: “ + pricePattern.format( price2 ) ); System.out.println( "\nThe third price is: “ + pricePattern.format( price3 ) ); System.out.println( "\nThe fourth price is: “ + pricePattern.format( price4 ) ); System.out.println( "\nThe fifth price is: “ + pricePattern.format( price5 ) );

  49. // instantiate another DecimalFormat object for printing percentages DecimalFormat percentPattern = new DecimalFormat( "#0.0%" ); double average = .980; System.out.println( "\nThe average is: “ + percentPattern.format( average ) ); // notice that the average is multiplied by 100 to print a percentage. // now instantiate another DecimalFormat object for printing time as two digits DecimalFormat timePattern = new DecimalFormat( "00" ); int hours = 5, minutes = 12, seconds = 0; System.out.println( "\nThe time is “ + timePattern.format( hours ) + ":" + timePattern.format( minutes ) + ":“ + timePattern.format( seconds ) ); // now instantiate another DecimalFormat object for printing numbers in the millions. DecimalFormat bigNumber = new DecimalFormat( "#,###,###" ); int millions = 1234567; System.out.println( "\nmillions is “ + bigNumber.format( millions ) ); } }

  50. Output The first price is: $78.67 The second price is: $34.50 The third price is: $0.33 The fourth price is: $3.00 The fifth price is: $100.23 The average is: 98.0% The time is 05:12:00 millions is 1,234,567

More Related