Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 41 Defining Classes and Methods Chapter 4.

Similar presentations


Presentation on theme: "Chapter 41 Defining Classes and Methods Chapter 4."— Presentation transcript:

1 Chapter 41 Defining Classes and Methods Chapter 4

2 2 Objectives become familiar with the concept of a class and an object that instantiates the class learn how to define classes in Java learn how to define and use methods in Java learn how to create objects in Java learn how parameters work in Java

3 Chapter 43 Objectives, cont. learn about information hiding and encapsulation become familiar with the notion of a reference (to understand class variables and class parameters) (optional) learn more about applets

4 Chapter 44 Outline Class and Method Definitions Information Hiding and Encapsulation Objects and Reference (optional) Graphics Supplement

5 Chapter 45 Class and Method Definitions: Outline Class Files and Separate Compilation Instance Variables Using Methods void Method Definitions Methods that Return a Value Accessing Instance Variables Local Variables

6 Chapter 46 Class and Method Definitions: Outline, cont. Blocks Parameters of a Primitive Type Class and Method Definition Syntax

7 Chapter 47 Basic Terminology Objects can represent almost anything. A class defines a kind of object. –It specifies the kinds of data an object of the class can have. –It provides methods specifying the actions an object of the class can take. An object satisfying the class definition instantiates the class and is an instance of the class.

8 Chapter 48 Basic Terminology, cont. The data items and the methods are referred to as members of the class. We will call the data items associated with an object the instance variables of that object (i.e. that instance of the class).

9 Chapter 49 A Class as an Outline

10 Chapter 410 A UML Class Diagram

11 Chapter 411 Class Files and Separate Compilation Each Java class definition should be in a file by itself. –The name of the file should be the same as the name of the class. –The file name should end in.java A Java class can be compiled before it is used in a program –The compiled byte code is stored in a file with the same name, but ending in.class

12 Chapter 412 Class Files and Separate Compilation, cont. If all the classes used in a program are in the same directory as the program file, you do not need to import them.

13 Chapter 413 Example class SpeciesFirstTry

14 Chapter 414 Example, contd. –The modifier public associated with the instance variables should be replaced with the modifier private, as we will do later in the chapter.

15 Chapter 415 Example, contd. class SpeciesFirstTryDemo –Each object of type SpeciesFirstTry has its own three instance variables

16 Chapter 416 Using Methods two kinds of methods: –methods that return a single value (e.g. nextInt ) –methods that perform some action other than returning a single value (e.g println ), called void methods

17 Chapter 417 Methods That Return a Value example int next = keyboard.nextInt(); –keyboard is the calling object. –You can use the method invocation any place that it is valid to use of value of the type returned by the method.

18 Chapter 418 Methods That Do Not Return a Value example System.out.println(“Enter data:”); –System.out is the calling object. The method invocation is a Java statement that produces the action(s) specified in the method definition. –It is as if the method invocation were replaced by the statements and declarations in the method definition.

19 Chapter 419 void Method Definitions example public void writeOuput() { System.out.println(“Name: “ + name); System.out.println(“Age: “ + age); } Such methods are called void methods.

20 Chapter 420 Method Definitions All method definitions belong to some class. All method definitions are given inside the definition of the class to which they belong. If the definition of the method begins with public void, it does not return a value. –public indicates that use is unrestricted. –void indicates that the method does not return a value.

21 Chapter 421 Method Definitions, cont. The parentheses following the method name contain any information the method needs. The first part of the method definition is called the heading. The remainder of the method is called the body, and is enclosed in braces {}. Statements or declarations are placed in the body.

22 Chapter 422 The Method main A program is a class that has a method named main. The programs we have seen so far have no instance variables and no methods other than method main. Programs can have instance variables and other methods.

23 Chapter 423 Defining Methods That Return a Value example public int fiveFactorial(); { int factorial = 5*4*3*2*1; return factorial; } As before, the method definition consists of the method heading and the method body. –The return type replaces void.

24 Chapter 424 Defining Methods That Return a Value, cont. The body of the method definition must contain return Expression; –This is called a return statement. –The Expression must produce a value of the type specified in the heading. The body can contain multiple return statements, but a single return statement makes for better code.

25 Chapter 425 Naming Methods Use a verb to name a void method. –void methods typically perform some action(s). (e.g. getAge ) Use a noun to name a method that returns a value. –Methods that return a value are used like a value. (e.g. fiveFactorial ) Observe the convention of starting the method name with a lowercase letter.

26 Chapter 426 Using return in a void Method form return; use –to end the invocation of the method, usually prematurely, to deal with some problem caution –Almost always, there are better ways to deal with a potential problem.

27 Chapter 427 public Method Definitions syntax for a void method public void Method_Name(Parameters); { }

28 Chapter 428 public Method Definitions syntax for methods that return a value public Return_Type Method_Name(Parameters); { < statement(s), including a return statement > }

29 Chapter 429 Accessing Instance Variables Outside the class definition, a public instance variable is accessed with –the name of an object of the class –a dot (.) –the name of the instance variable. –Example: myBestFriend.name = “Lara”; Inside the definition of the same class only the name of the instance variable is used. –Example: name = keyboard.nextLine();

30 Chapter 430 Accessing Instance Variables, cont. equivalent assignment statements: name = keyboard.nextLine(); and this.name = keyboard.nextLine(); –The keyword this stands for the calling object - the object that invokes the method.

31 Chapter 431 Local Variables A variable declared within a method is called a local variable. –Its meaning is “local to” (confined to) the method definition. Variables with the same name declared within different methods are different variables. A local variable exists only as long as the method is active.

32 Chapter 432 Local Variables, cont. class BankAccount class LocalVariablesDemoProgram

33 Chapter 433 Blocks The terms block and compound statement both refer to a set of Java statements enclosed in braces {}. A variable declared within a block is local to the block. –When the block ends, the variable disappears. If you intend to use the variable both inside and outside the block, declare it outside the block.

34 Chapter 434 Variables in for Statements The loop control variable can be declared outside the for statement int n; for (n = 1; n <10, n++) in which case the variable n still exists when the for statement ends or

35 Chapter 435 Variables in for Statements, cont. The loop control variable can be declared inside the for statement for (int n = 1; n <10, n++) in which case the variable n ceases to exist when the for statement ends

36 Chapter 436 Parameters of a Primitive Type Often it is convenient to pass one or more values into a method and to have the method perform its actions using those values. The values are passed in as arguments (or actual parameters) associated with the method invocation.

37 Chapter 437 Parameters of a Primitive Type, cont. The method receives the values and stores them in its formal parameters (or simply parameters). –A method invocation assigns the values of the arguments (actual parameters) to the corresponding formal parameters (parameters). –This is known as the call-by-value mechanism.

38 Chapter 438 Parameters of a Primitive Type, cont. The formal parameters exist as long as the method is active.

39 Chapter 439 Parameters of a Primitive Type, cont. Generally, the type of each argument must be the same as the type of the corresponding formal parameter. Java will perform automatic type conversion for an argument that appears to the left of a formal parameter it needs to match byte --> short --> int --> long --> float --> double

40 Chapter 440 Parameters of a Primitive Type, cont. An argument in a method invocation can be –a literal such as 2 or ‘A’ –a variable –any expression that yields a value of the appropriate type. A method invocation can include any number of arguments; the method definition contains a corresponding number of formal parameters, each preceded by its type.

41 Chapter 441 Parameters of a Primitive Type, cont. anObject.doStuff(42, 100, 9.99, ‘Z’); public void doStuff(int n1, int n2, double d1, char c1); –arguments and formal parameters are matched by position Everything said about arguments and formal parameters applies to methods that return a value as well as to void methods.

42 Chapter 442 Method with a Parameter class SpeciesSecondTry

43 Chapter 443 Using a Method with a Parameter class SpeciesSecondTryDemo

44 Chapter 444 Class and Method Definition Syntax public class Class_Name { Instance_Variable_Declaration_1; Instance_Variable_Declaration_2; … Method_Definition_1 Method_Definition_2... }

45 Chapter 445 Class and Method Definition Syntax, cont. public Type_Name_Or_void Method_Name(Parameter_List); where Parameter_List consists of –a list of one or more formal parameter names, each preceded by a type and separated by commas or –no formal parameters at all

46 Chapter 446 Information Hiding and Encapsulation: Outline Information Hiding Precondition and Postcondition Comments The public and private Modifiers Encapsulation Automatic Documentation with javadoc UML Class Diagrams

47 Chapter 447 Information Hiding “Information overload” is avoided by suppressing or hiding certain kinds of information, making the programmer’s job simpler and the code easier to understand. A programmer can use a method defined by someone else without knowing the details of how it works (e.g. the println method) –She or he needs to know what the method does, but not how it does it.

48 Chapter 448 Information Hiding, cont. What the method contains is not secret, and maybe not even interesting. Viewing the code does not help you use the method and may distract you from the task at hand. Designing a method so that it can be used without knowing how it performs its task is called information hiding or abstraction.

49 Chapter 449 Precondition and Postcondition Comments The precondition for a method states the condition(s) that must be true before the method is invoked. –If the precondition is not met, the method should not be used and cannot be expected to perform correctly. The postcondition describes the result(s) of the method invocation.

50 Chapter 450 Precondition and Postcondition Comments, cont. If the precondition is satisfied and the method is executed, the postcondition will be true. Example /** Precondition: The instance variables of the calling object have values. Postcondition: The values of the instance variables are displayed. */

51 Chapter 451 Precondition and Postcondition Comments, cont. If a returned value is the only postcondition, the postcondition often is not stated. The statement of the precondition and the postcondition typically precede the associated method in the form of a javadoc comment ( /**…*/ )

52 Chapter 452 Assertions An assertation is a statement about the state of the program. Precondition and postcondition comments are examples of assertions. Assertions can occur elsewhere in programs, such as after a block.

53 Chapter 453 Assertions, cont. A check can be inserted to determine if an assertion is true and, if not, to stop the program and output an error message. An assertion check has the form assert Boolean_Expression; e.g. assert n >= limit; –if Boolean_Expression evaluates to false, the program ends and outputs an error message.

54 Chapter 454 Assertions, cont. Assertion checking can be turned on or off. Normally, programs run with assertion checking turned off. See your IDE documentation to learn how to set options for assertion checking.

55 Chapter 455 The public and private Modifiers The instance variables of a class should not be declared public. –Typically, instance variables are declared private. An instance variable declared public can be accessed and changed directly, with potentially serious integrity consequences. –Declaring an instance variable private protects its integrity.

56 Chapter 456 The public and private Modifiers, cont. Analogy: An ATM permits deposits and withdrawals, both of which affect the account balance, but it does not permit an account balance to be accessed and changed directly. If an account balance could be accessed and changed directly, a bank would be at the mercy of ignorant and unscrupulous users.

57 Chapter 457 The private Modifier The private modifier makes an instance variable inaccessible outside the class definition. But within the class definition, the instance variable remains accessible and changeable. This means that the instance variable can be accessed and changed only via the methods accompanying the class.

58 Chapter 458 The private Modifier, cont. class SpeciesThirdTry

59 Chapter 459 The private Modifier, cont. Statements such as System.out.println (secretSpecies.population); are no longer valid.

60 Chapter 460 The private Modifier, cont. Methods in a class also can be private. Methods declared private cannot be invoked outside the class definition, but can be invoked within the definition of any other method in the class. A method invoked only within the definition of other methods in the class should be declared private.

61 Chapter 461 Accessor and Mutator Methods Appropriate access to an instance variable declared private is provided by an accessor method which is declared public. –Typically, accessor methods begin with the word get, as in getName. Mutator methods should be written to guard against inappropriate changes.

62 Chapter 462 Accessor and Mutator Methods class SpeciesFourthTry

63 Chapter 463 Accessor and Mutator Methods, cont. Appropriate changes to an instance variable declared private are provided by an mutator method which is declared public. –Typically, mutator methods begin with the word set, as in setName.

64 Chapter 464 Accessor and Mutator Methods, cont. class SpeciesFourthTryDemo

65 Chapter 465 Programming Example class Purchase

66 Chapter 466 Programming Example, contd. class Purchase, contd.

67 Chapter 467 Programming Example class PurchaseDemo

68 Chapter 468 Encapsulation Encapsulation is the process of hiding details of a class definition that are not needed to use objects of the class. Encapsulation is a form of information hiding.

69 Chapter 469 Encapsulation, cont. When done correctly, encapsulation neatly divides a class definition into two parts: –the user interface which communicates everything needed to use the class –the implementation consisting of all the members of the class. A class defined this way is said to be well- encapsulated.

70 Chapter 470 The User Interface The user interface consists of –the headings for the public methods –the defined public constants –comments telling the programmer how to use the public methods and the defined public constants. The user interface contains everything needed to use the class.

71 Chapter 471 The Implementation The implementation consists of –the private instance variables –the private defined constants –the definitions of public and private methods. The Java code contains both the user interface and the implementation. Imagine a wall between the user interface and the implementation.

72 Chapter 472 Encapsulation

73 Chapter 473 Encapsulation Guidelines Precede the class definition with a comment that shapes the programmer’s view of the class. Declare all the instance variables in the class private. Provide appropriate public accessor and mutator methods.

74 Chapter 474 Encapsulation Guidelines, cont. Provide public methods to permit the programmer to use the class appropriately. Precede each public method with a comment specifying how to use the method. Declare methods invoked only by other methods in the class private. Use /*...*/ or /**...*/ for user interface comments and // for implementation comments.

75 Chapter 475 Encapsulation Characteristics Encapsulation should permit implementation changes (improvements, modifications, simplifications, etc.) without requiring changes in any program or class that uses the class. Encapsulation combines the data and the methods into a single entity, “hiding” the details of the implementation.

76 Chapter 476 ADT An abstract data type (ADT) is basically the same as a well-encapsulated class definition.

77 Chapter 477 Automatic Documentation with javadoc A program named javadoc automatically generates user interface documentation. The documentation contains everything needed to use the class(es). Properly commented class definitions (using /** … */ ) can be used to produce and display the user interface.

78 Chapter 478 Automatic Documentation with javadoc The course text can be understood without learning or using javadoc. Java programs can be written, compiled, and executed without using javadoc. Documents produced by javadoc must be read using a Web browser or other HTML viewer. Nevertheless, javadoc is both useful and easy to use.

79 Chapter 479 UML Class Diagrams UML diagrams are mostly self-explanatory. A plus sign ( + ) indicates a public instance variable or method. A minus sign ( - ) indicates a private instance variable or method. Typically, the class diagram is created before the class is defined. A class diagram outlines both the interface and the implementation.

80 Chapter 480 UML Class Diagrams, cont.

81 Chapter 481 Objects and Reference: Outline Variables of a Class Type and Objects Boolean-Valued Methods Class Parameters Comparing Class Parameters and Primitive- Type Parameters

82 Chapter 482 Variables Variables of a class type name objects, which is different from how primitive variables store values. All variables are implemented as memory locations. –The value of a variable of a primitive type is stored in the assigned location. –The value of a variable of a class type is the address where a named object of that class is stored.

83 Chapter 483 Variables, cont. A value of any particular primitive type always requires the same amount of storage. –example: a variable of type int always requires 4 bytes. An object of a class type might be arbitrarily large. –An object of type String might be empty, or might contain 1, 120, 5280, or more characters.

84 Chapter 484 Variables, cont. However, there is always a limit on the size of an address. The memory address where an object is stored is called a reference to the object. Variables of a class type behave differently from variables of a primitive type.

85 Chapter 485 Variables of a Primitive Type Only one variable of a primitive type is associated with the memory location where the value of the variable is stored.

86 Chapter 486 Variables of a Class Type However, multiple variables of a class type can contain the memory location where an object is stored. –The object can be accessed and potentially changed using any of these variables. –All these variables contain the same reference and name the same object. Variables of a class type referencing the same memory location are called aliases.

87 Chapter 487 Variables of a Class Type, cont. When one variable of a class type is assigned to another variable of a compatible class type, the memory address is copied from one variable to another and the two variables become aliases of one another. The numeric values of these memory addresses generally are not available to the programmer nor are they needed by the programmer.

88 Chapter 488 Variables of a Class Type, cont.

89 Chapter 489 Allocating Memory for a Reference and an Object A declaration such as SpeciesFourthTry s; creates a variable s that can hold a memory address. A statement such as s = new SpeciesFourthTry(); allocates memory for an object of type SpeciesFourthTry.

90 Chapter 490 == with Variables of a Class Type

91 Chapter 491 == with Variables of a Class Type, cont. When used with variables of a class type, == tests if the variables are aliases of each other, not if they reference objects with identical data. To test for equality of objects in the intuitive sense, define and use an appropriate equals method.

92 Chapter 492 == with Variables of a Class Type, cont. class Species

93 Chapter 493 == with Variables of a Class Type, cont. class SpeciesEqualsDemo

94 Chapter 494 Method equals The definition of method equals depends on the circumstances. –In some cases, two objects may be “equal” when the values of only one particular instance variable match. –In other cases, two objects may be “equal” only when the values of all instance variables match. Always name the method equals.

95 Chapter 495 Programming Example class Species

96 Chapter 496 Programming Example, contd. class Species, contd.

97 Chapter 497 Programming Example, cont.

98 Chapter 498 Boolean-Valued Methods A method that returns a value of type boolean is called a boolean-valued method. Method equals produces and returns a value of type boolean. The invocation of a boolean-valued method can be used as the condition of an if-else statement, a while statement, etc.

99 Chapter 499 Boolean-Valued Methods, cont. The value returned by a boolean-valued method can be stored in a variable boolean areEqual = s1.equals(s2); Any method that returns a boolean value can be used in the same way.

100 Chapter 4100 Class Parameters Recall –When the assignment operator is used with objects of a class type, a memory address is copied, creating an alias. –When the assignment operator is used with a primitive type, a copy of the primitive type is created.

101 Chapter 4101 Class Parameters, cont. –When a parameter in a method invocation is a primitive type, the corresponding formal parameter is a copy of the primitive type.

102 Chapter 4102 Class Parameters, cont. When a parameter in a method invocation is a reference to a class type (i.e. a named object), the corresponding formal parameter is a copy of that reference (i.e. an identically valued reference to the same memory location).

103 Chapter 4103 Class Parameters, cont. Example if (s1.equals(s2)) … public boolean equals (Species otherObject) causes otherObject to become an alias of s2, referring to the same memory location, which is equivalent to otherObject = s2;

104 Chapter 4104 Class Parameters, cont. Any changes made to the object named otherObject will be done to the object named s2, and vice versa, because they are the same object. –If otherObject is a formal parameter of a method, the otherObject name exists only as long as the method is active.

105 Chapter 4105 Comparing Class Parameters and Primitive-Type Parameters A method cannot change the value of a variable of a primitive type passed into the method. A method can change the value(s) of the instance variable(s) of a class type passed into the method.

106 Chapter 4106 Comparing Class Parameters and Primitive-Type Parameters, cont. class DemoSpecies

107 Chapter 4107 Comparing Class Parameters and Primitive-Type Parameters, cont. class ParametersDemo

108 Chapter 4108 (optional) Graphics Supplement: Outline The Graphics Class The init Method Adding Labels to an Applet

109 Chapter 4109 The Graphics Class An object of the class Graphics represents an area of the screen. The class Graphics also has methods that allow it do draw figures and text in the area of the screen it represents.

110 Chapter 4110 The Graphics Class, cont.

111 Chapter 4111 The Graphics Class, cont. A Graphics object has instance variables that specify an area of the screen In examples seen previously, the Graphics object represented the area corresponding to the inside of an applet.

112 Chapter 4112 The Graphics Class, cont. When an applet is run, a suitable Graphics object is created automatically and is used as an argument to the applet’s paint method when the paint method is (automatically) invoked. –The applet library code does all this for us. –To add this library code to an applet definition, use extends JApplet

113 Chapter 4113 Programming Example class MultipleFaces

114 Chapter 4114 Programming Example, contd. class MultipleFaces, contd.

115 Chapter 4115 Programming Example, cont. –The code for drawing most of the face is placed in private method drawFaceSansMouth to save multiple repetitions of this code.

116 Chapter 4116 Programming Example, cont.

117 Chapter 4117 The init Method An init method can be defined when an applet is written. The method init (like the method paint ) is called automatically when the applet is run. –The paint method is used only for things like drawing. –All other actions in an applet (adding labels, buttons, etc.) either occur or start in the init method.

118 Chapter 4118 Adding Labels to an Applet A label is another way to add text to an applet.

119 Chapter 4119 Adding Labels to an Applet, cont. class LabelDemo

120 Chapter 4120 Adding Labels to an Applet, cont.

121 Chapter 4121 The Content Pane Think of the content pane as inside of the applet. Container contentPane = getContentPane(); When components are added to an applet, they are added to its content pane. The content pane is an object of type Container.

122 Chapter 4122 The Content Pane, cont. A named content pane can do things such as setting color contentPane.setBackground(Color.WHITE); or specifying how the components are arranged contentPane.setLayout (new FlowLayout());

123 Chapter 4123 The Content Pane, cont. or adding labels JLabel label1 = new JLabel(“Hello”); contentPane.add(label1);

124 Chapter 4124 Summary You have become familiar with the concept of a class and an object that instantiates the class. You have learned how to define classes in Java. You have learned how to define and use methods in Java. You have learned how to create objects in Java

125 Chapter 4125 Summary, cont. You have learned how parameters work in Java. You have learned about information hiding and encapsulation. You have become familiar with the notion of a reference (to understand class variables and class parameters). (optional) You have learned more about applets.


Download ppt "Chapter 41 Defining Classes and Methods Chapter 4."

Similar presentations


Ads by Google