Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java™ How to Program, 10/e © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Similar presentations


Presentation on theme: "Java™ How to Program, 10/e © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved."— Presentation transcript:

1 Java™ How to Program, 10/e © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

2

3  Topics covered in this chapter ◦ Classes ◦ Objects ◦ Methods ◦ Parameters ◦ double primitive data type for representing floating points numbers © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.3

4  Each class you create becomes a new data type that can be used to declare variables and create objects.  You can code new classes as needed; this is one reason Java is known as an extensible language.  Create a new class ( Account).  Use it to create an object.  ch03\fig03_01_02\Account.java  ch03\fig03_01_02\AccountTest.java © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

5 3.2.1 Account Class with an Instance Variable, a set Method and a get Method - I

6 Class Declaration  Each class declaration that begins with the access modifier public must be stored in a file that has the same name as the class and ends with the.java filename extension.  Every class declaration contains keyword class followed immediately by the class’s name.  Keyword public is an access modifier. ◦ Indicates that the class is “available to the public” – visible to any Java code. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

7 Identifiers and Camel Case Naming  Class, method and variable names are identifiers.  By Java naming conventions all use camel case names.  Class names begin with an uppercase letter, and method and variable names begin with a lowercase letter. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

8 Instance Variable name  An object has attributes that are implemented as instance variables and carried with it throughout its lifetime.  Attributes are also called fields, data fields, data members of the class  Instance variables exist before methods are called on an object, while the methods are executing and after the methods complete execution.  A class normally contains one or more methods that manipulate the instance variables that belong to particular objects of the class.  Instance variables are declared inside a class declaration but outside the bodies of the class’s method declarations.  Each object (instance) of the class has its own copy of each of the class’s instance variables. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

9

10 Access Modifiers public and private  Most instance variable declarations are preceded with the keyword private, which is an access modifier.  Variables or methods declared with access modifier private are accessible only to methods of the class in which they’re declared.  private modifier prevents instance variables from being modified accidentally by a class in another part of the program.  setXXX (mutator) and getXXX (accessor) methods may be coded to access instance variables. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

11 setName Method of Class Account  Parentheses after the method name are required – any identifier without parentheses is either a variable, a constant, or a class name.  Parameters are declared in a comma separated parameter list, which is located inside the parentheses that follow the method name in the method declaration.  Multiple parameters are separated by commas.  Each parameter must specify a type followed by a variable name. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

12  Empty parentheses after the method name indicate that the method does not require additional information to perform its task.  Together, everything in the first line of the method is typically called the method header, signature, or prototype.  Every method’s body is delimited by left and right braces.  The method body contains one or more statements that perform the method’s task.  OOP rule: one method – one task!!! © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

13 Parameters Are Local Variables  Variables declared in the body of a particular method are local variables and can be used only in that method.  Memory space for local variables is allocated only during the execution of the method.  When a method terminates, the values of its local variables are lost as memory is released (de-allocated).  Method’s parameters alsp are local variables of the method. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

14 setName Method Body  Every method’s body is delimited by left and right braces ( { and } ).  Each method’s body contains one or more statements that perform the method’s task(s). © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

15

16 getName Method of Class Account  Method name follows the return type in the method declaration.  The method’s return type specifies the type of data returned to a method’s caller.  Keyword void indicates that a method will perform a task but will not return (i.e., give back) any information to its calling method when it completes its task.  When a method that specifies a return type other than void is called and completes its task, the method must return a result to its calling method. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

17  The return statement passes a value from a called method back to its caller.  Classes often provide public methods to allow the class’s clients to set or get private instance variables.  The names of these methods need not begin with set or get, but this naming convention is recommended. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

18  Class methods can (and should) use class attributes even though these attributes are not declared in any of the methods. ◦ Can use an instance variable of the class in each of the class methods. ◦ Exception to this are static methods.  The order in which methods are declared in a class does not determine when they are called at execution time.  One method of a class can call another method of the same class by using just the method name. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

19  setXXX and getXXX methods ◦ A class’s private fields can be manipulated only by the class’s methods. ◦ The code that uses an object must call the class’s public methods to manipulate the private fields of an object of the class. ◦ Classes may provide public methods to allow clients to set (i.e., assign values to) or get (i.e., obtain the values of) private instance variables. ◦ Convention - the names of these methods should begin with set or get followed by the variable name with the first letter capitalized,. ◦ setXXX methods are usually called modifier methods. ◦ getXXX methods are usually called accessor methods. ◦ Provide only if required for the code usage. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

20 Driver Class AccountTest  A class that creates an object of another class, then calls the object’s methods, is a driver class.  Class declarations in Java include: ◦ Access modifier. ◦ Keyword class. ◦ Class name. ◦ A matching pair of left and right braces. ◦ Code inside the class body. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

21

22

23 Scanner Object for Receiving Input from the User  Scanner method nextLine reads characters until a newline character is encountered, then returns the characters as a String.  Scanner method next reads characters until any white space character is encountered, then returns the characters as a String. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

24 Instantiating an Object: Keyword new and Constructors  A class instance creation expression begins with keyword new and creates a new object.  A constructor is codrd similar to a method but is called by the new operator to initialize an object’s instance variables at the time the object is created. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

25 Calling Class Account ’s getName Method  To call a method of an object, follow the object name by a dot separator, the method name and a set of parentheses containing the method’s arguments. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

26

27 null is the Default Initial Value for String Variables  Method’s local variables are not automatically initialized.  Every instance variable has a default initial value provided by Java compiler when you do not specify the instance variable’s initial value.  The default value for an instance variable of type String (and all reference types) is null.  Class fields are not required to be explicitly initialized before they are used in a program, unless they must be initialized to values other than their default values. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

28 Calling Class Account ’s setName Method  A method call supplies values known as arguments for each of the method’s parameters.  Each argument’s value is assigned to the corresponding parameter in the method header.  The number of arguments in a method call must match the number of parameters in the method declaration’s parameter list.  Arguments and parameters are paired left to right.  The argument types in the method call must be consistent (assignment compatible) with the types of the corresponding parameters in the method’s declaration. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

29  An argument is a value we pass to a method.  A parameter is a placeholder in the called method to hold the value of the passed argument.  A parameter is also called a formal parameter and an argument - an actual parameter. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

30 30 Method Declaration ( ){ } public void displayMessage ( String courseName ) { System.out.printf( "Welcome to the grade book for\n%s!\n", courseName ); } Statements Modifier Return Type Method Name Parameters © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

31  The javac command can compile multiple classes at once.  Simply list the source code filenames after the command with each filename separated by a space from the next.  If the directory containing the app includes only one application’s files, you can compile all of its classes with the command javac *.java.  The asterisk ( * ) in *.java indicates that all files in the current directory ending with the filename extension “.java ” should be compiled. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

32 Top Compartment  In the UML, each class is modeled in a class diagram as a rectangle with three compartments. The top one contains the class’s name centered horizontally in boldface. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

33

34 Middle Compartment  The middle compartment contains the class’s attributes, which correspond to instance variables in Java. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

35 Bottom Compartment  The bottom compartment contains the class’s operations, which correspond to methods and constructors in Java.  The UML represents instance variables as an attribute name, followed by a colon and the type.  Private attributes are preceded by a minus sign ( – ) in the UML.  The UML models operations by listing the operation name followed by a set of parentheses.  A plus sign ( + ) in front of the operation name indicates that the operation is a public one in the UML (i.e., a public method in Java). © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

36 Return Types  The UML indicates an operation’s return type by placing a colon and the return type after the parentheses following the operation name.  UML class diagrams do not specify return types for operations that do not return values.  Declaring instance variables private is known as data hiding or information hiding. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

37 Parameters  The UML models a parameter of an operation by listing the parameter name, followed by a colon and the parameter type between the parentheses after the operation name © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

38 static Method main  The main method is called automatically by the Java Virtual Machine (JVM) when you execute an application.  You must call methods other than main explicitly to tell them to perform their tasks.  A key part of enabling the JVM to locate and call method main to begin the app’s execution is the static keyword, which indicates that main is a static method that can be called without first creating an object of the class in which the method is declared. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

39  A static method (such as main ) is special ◦ It can be called without first creating an object of the class in which the method is declared.  Typically, you cannot call a method that belongs to another class until you create an object of that class.  Declare a variable of the class type ◦ Each new class you create becomes a new Java data type that can be used to declare variables and create objects. ◦ You declare new class types as needed; this is one reason why Java is known as an extensible language. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

40  Any Java class can contain a main method. ◦ The JVM invokes the main method only in the class used to execute the application. ◦ If multiple classes contain main, then one that is invoked is the one in the class named in the java command call to the JVM. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

41 Notes on import Declarations  Most classes you’ll use in Java programs must be imported explicitly.  There’s a special relationship between classes that are compiled in the same directory.  By default, such classes are considered to be in the same package.  Classes in the same package are implicitly imported into the source code files of other classes in that package. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

42  An import declaration is not required when one class in a package uses another in the same package.  An import declaration is not required if you always refer to a class with its fully qualified class name, which includes its package name and class name.  Classes System and String are in package java.lang ◦ Implicitly imported into every Java program. ◦ Can use the java.lang classes without explicitly importing them. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

43

44  Declaring instance variables private is known as encapsulation, data hiding or information hiding. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

45

46 3.2.7 Software Engineering with private Instance Variables and public set and get Methods - II

47  Java data types are divided into two categories: primitive types and reference types.  The 8 Java primitive types are boolean, byte, char, short, int, long, float and double.  All other types are reference types, so classes, which specify the types of objects, are reference types.  A primitive type variable can store exactly one value of its declared type at a time.  Primitive type instance variables are initialized by default.  Variables of types byt e, char, short, int, long, float and double are initialized to 0. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

48  Variables of type boolean are initialized to false.  Reference type variables (called references) store the location of an object in the computer’s memory.  Such variables refer to objects in the program.  The object that’s referenced may contain many instance variables and methods.  Reference type instance variables are initialized by default to the value null.  A reference to an object is required to invoke an object’s methods.  A primitive type variable does not refer to an object and therefore cannot be used to invoke a method. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

49  You can and should specify your own initial values for all primitive or reference instance variables by assigning the variable a value in its declaration (or in the class’s constructor).  Each class you declare can optionally provide a constructor with parameters that can be used to initialize an object of a class when the object is created.  Java requires a single constructor call for every object that’s created. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

50  When an object of a class is created, its instance variables are initialized by default.  Each class can and should include one or more constructors that properly initialize an object of a class when the object is created.  Operator new requests memory from the system to store an object, then calls the corresponding class’s constructor to initialize the object. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

51  Constructor is called once and only once for every object created.  A constructor must have the same name as the class.  ch03\fig03_05_06\Account.java  ch03\fig03_01_06\AccountTest.java © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

52

53 3.4.1 Declaring an Account Constructor for Custom Object Initialization - II

54 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 3.4.2 Class AccountTest : Initializing Account Objects When They’re Created - I

55  The compiler inserts a default (no-argument) constructor with no parameters for any class that does not explicitly include a constructor. ◦ Instance variables are initialized to their default values.  Always provide your own constructors to specify meaningful instance field initializations for objects of your class.  A constructor’s parameter list specifies the data it requires to perform its task – instance fields’ initialization. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

56 Normally, constructors are declared public. Constructors Cannot Return Values  Constructor declaration can specify parameters but not return types. Default Constructor  If a class does not define constructors, the compiler provides a default constructor with no parameters, and the class’s instance variables are initialized to their default values. There’s No Default Constructor in a Class That Declares a Constructor  If you declare a constructor for a class, the compiler will not create a default constructor for that class. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

57

58 Adding the Constructor to Class Account ’s UML Class Diagram  The UML models constructors in the third compartment of a class diagram.  To distinguish a constructor from a class’s operations, the UML places the word “constructor” between guillemets (« and ») before the constructor’s name.  List constructors before other operations in the third compartment. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

59

60 60 Always executed by JVM when a new instance of the class is created. public ( ){ } public GradeBook( String name ) { courseName = name; // initializes courseName } // end constructor Statements Modifier Class Name Parameters Constructor Basics - I © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

61 61  The name of a constructor must be the same as the name of the class.  If no constructor is defined for a class, then the Java compiler will include a default (no-argument) constructor.  The default constructor will have the following form: public ( ){ } public GradeBook( ) { }  It is recommended to provide an explicit default constructor to prevent potential inheritance related problems. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

62 62  A constructor does not have a return type.  It is possible to create multiple (overloaded) constructors for a class, as long as the constructors have different signatures which means either:  A different number of parameters, or  Different data types for the parameters if the number of parameters is the same. Constructor Basics - III © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

63 63 Template for Class Definition class { } Import Statements Class Comments Class Name Data Members Methods (incl. Constructors) Methods (incl. Constructors) © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

64  A floating point number is a number with a decimal point.  Java provides two primitive types for storing floating point numbers in memory: float and double.  Variables of type float represent single precision floating point numbers and have up to seven significant digits.  Variables of type double represent double precision floating point numbers.  double variables require twice as much memory as float variables and provide 15 significant digits - more than double the precision of float variables. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

65  Floating point literals (such as 7.33 and 0.0975) are of type double by default.  ch03\fig03_08_09\Account.java  ch03\fig03_08_09\AccountTest.java © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

66 3.5.1 Account Class with a balance Instance Variable of Type double

67 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

68

69 3.5.2 AccountTest Class to Use Class Account - I

70 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

71

72

73  Scanner method nextDouble returns a double value entered by the user.  System.out.printf ◦ Format specifier %.2f ◦ %f is used to output values of type float or double. ◦.2 represents the number of decimal places ( 2 ) to output to the right of the decimal point (also known as the number’s display precision). ◦ Any floating point value output with %.2f will be rounded to the hundredths position. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

74 3.5.2 AccountTest Class to Use Class Account - III

75  The default value for an instance variable of type double is 0.0, and the default value for an instance variable of type int is 0. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

76 3.5.2 AccountTest Class to Use Class Account - V

77 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 3.5.2 AccountTest Class to Use Class Account - VI

78 78 The six Java numeric data types differ in the precision of values they can store in memory. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

79 79  Never use float in your code – double should be used to provide necessary precision.  Don ’ t use floating point numbers as loop control variables.  Never compare floating point numbers for exact equality 1.0/3 + 1.0/3 + 1.0/3 != 1.0 Floating Point Numbers in Programs © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

80 3.6 GUI and Graphics Case Study: Using Dialog Boxes - I

81 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 3.6 GUI and Graphics Case Study: Using Dialog Boxes - II  Many applications use windows or dialog boxes (also called dialogs) to display output.  Typically, dialog boxes are windows in which programs display important messages to users.  Class JOptionPane provides prebuilt dialog boxes that enable programs to display windows containing messages - such windows are called message dialogs.  ch03\fig03_12\Dialog1.java

82 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

83 3.6 GUI and Graphics Case Study: Using Dialog Boxes - III  Package javax.swing contains many classes that help you create graphical user interfaces (GUIs).  GUI components facilitate data entry by a program’s user and presentation of outputs to the user.  JOptionPane method showMessageDialog displays a dialog box containing a message. ◦ Requires two arguments. ◦ The first helps the Java application determine where to position the dialog box.  If the first argument is null, the dialog box is displayed at the center of your screen. ◦ The second argument is the String to display in the dialog box.

84 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 3.6 GUI and Graphics Case Study: Using Dialog Boxes - IV  JOptionPane method showMessageDialog is a static method.  Such methods often define frequently used tasks.  Typically called by using method’s class name followed by a dot (. ) and the method name, as in ClassName. methodName ( arguments );  Notice that you do not need to create an object of class JOptionPane to use its static method showMessageDialog.

85 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 3.6 GUI and Graphics Case Study: Using Dialog Boxes - V  An input dialog allows the user to enter data into a program.  JOptionPane method showInputDialog displays an input dialog ◦ Contains a prompt and a field (known as a text field) in which the user can enter text.  Method showInputDialog returns a String containing the characters typed by the user.  If you press the dialog’s Cancel button or press the Esc key, the method returns null reference.  ch03\Fig03_13\NameDialog.java

86 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 3.6 GUI and Graphics Case Study: Using Dialog Boxes - VI  static String method format returns a formatted String.  Method format works like method System.out.printf, except that format returns the formatted String rather than displaying it in a command window.

87 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

88


Download ppt "Java™ How to Program, 10/e © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved."

Similar presentations


Ads by Google