1 / 218

Introduction to Computer Science

Introduction to Computer Science. Unit 7. Classes and Methods I Objects Instance Methods Formal Parameters, the Stack, Call-by-Value, Scope of Variables, Mutable vs. Immutable Classes Object Variables as References (i.e., addresses) Example: Encapsulation Tic-tac-toe board.

cili
Download Presentation

Introduction to Computer Science

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. Introduction to Computer Science Unit 7 • Classes and Methods I • Objects • Instance Methods • Formal Parameters, the Stack, Call-by-Value, Scope of Variables, Mutable vs. Immutable Classes • Object Variables as References (i.e., addresses) • Example: Encapsulation Tic-tac-toe board

  2. Once Again, With Feeling • We have already seen some examples of objects, instance variables, and instance methods • The purpose of this section is to go over the concepts in much more detail, to learn new things about objects and their use, and to see examples of their use

  3. An Object is a Collection of Attributes and Operations • An object encapsulates data values within a single entity, along with operations to be performed on those data values • An object’s behavior is often general enough to be reused in multiple situations • Classes, the basis of objects, provide the basis for deriving other classes through inheritance

  4. The Structure of Classes classname{ declarations constructor definitions method definitions } instance variablesand symbolic constants how to create and initialize objects how to manipulate those objects These parts of a class can actually be in any order

  5. Methods First • Two kinds of methods: Class methods and Instance methods • Math.sqrt is an example of a Class method; “Math” is the name of a class, and we invoke the sqrt method in that class • main is also a Class method • I’m still not going to talk more about Class methods now; only Instance methods in this lecture

  6. Methods Calling Methods • Each method contains a sequence of statements to be executed • When a method f( ) calls a method g( ), Java begins executing the statements of g( ) but remembers that it was in the middle of f( ) • When g( ) is done, Java returns to the executing f( ), continuing where it left off

  7. Methods Calling Methods:Execution is Nested void f ( ) { System.out.println(“Hi there!”); System.out.println(“Nice weather!”); ... obj.g( ); System.out.println(“That was fun!”); System.out.println(“Time to move on!”);} void g ( ) { System.out.println(“A!”); System.out.println(“B!”); System.out.println(“C!”); System.out.println(“D!”);}

  8. Of Course, Nesting can be to Multiple Levels void e ( ) {......obj.f( );...} 4 1 2 3 5 8 7 6 9 A key point is that Java remembers where it was, and resumes execution there when returning from a method call

  9. Methods Returning Values • Some methods return a value (int, double, boolean, etc.) • A method that returns a value can be used wherever Java wants a value of that type (e.g., in an expression)wage = sinp.readInt( ); • Use the statementreturnvalue;to return a value from a method, where the value is of the appropriate type

  10. Method Not Returning a Value • Other methods do not return a value, i.e., they return type void • A call to a method that returns no value constitutes a complete Java statementbill.printTime( ); • Use the statementreturn;to return from a void method, or you can just let the method execute until the end, and it will automatically return

  11. Formal Parameters • The heading of a method specifies the return type, and the identifier and type of each parameter to the method • These identifiers are called the formal parameters of the method • When the method is called, the call supplies the actual parameters (or arguments) of the call

  12. Formal Parameters of a Method boolean checkValue (int col, int row, int limit) returned typeof method nameof method three formal parametersof method, each of type int Call to checkValue( ) (as an expression):bill.checkValue(3, 7, 9)assigns 3, 7, and 9 to the formal parameters col, row, and limit, respectively; then executes the method

  13. Matching Arguments andFormal Parameters bill.checkValue(3, 7, 9) boolean checkValue (int col, int row, int limit) {if (row > limit) ...else ...} There must be an (exact) match between the number, order, and type of the actual parameters and the formal parameters (except for things like an int value being automatically converted to a double).

  14. Legal? double findValue (int start, double end, int limit) • bill.findValue(3, 5.0, 9) • bill.findValue(5.0, 3, 9) • bill.findValue(5, 3, 9) • bill.findValue(5, 3) • bill.findValue(5, 3, 9, 4) • bill.findValue(x, y, z)

  15. Local Variables • Instance methods can also have local variables, defined within the method (in addition to the class attributes) • These variables store values during the method’s executionboolean checkValue (int col, int row, int limit) {double d;if (row > limit) ...}

  16. Class Abstraction • The most important stage in writing a class is to get an abstraction of the class done first. • What does an object of this type represent? • What is its interface? • What is its internal state? • This means you have to know what should be the internal state (variables) and also the behavior/interface (methods) of the class before you start to write your class code.

  17. Objects and Classes • The relationship between Classes and Objects can be seen as the relationship between a blueprint/model and the actual object built from it. • Example: Blueprint of a house (class) and the house (object) • The class defines: • The type of data that will be held in an object • The code for the methods of the object • In order to use a class you must instantiate an object from it. • This corresponds to building the house from the blueprint • There may be many objects from a single class

  18. An Example Class • The Time class will be used to create objects the represent a time (hour and minute) within a day • It comes with methods for creating and manipulating hours and minutes • It has two internal integers, _hour (between 0 and 23), and _minute (between 0 and 59) Time _hour _minute Time addMinutes( int m ) void printTime( )

  19. Class Abstraction! • The Time class will be used to create objects the represent a time (hour and minute) within a day • What does an object of this type represent? • It comes with methods for creating and manipulating hours and minutes • What is its interface? • It has two internal integers, _hour (between 0 and 23), and _minute (between 0 and 59) • What is its internal state?

  20. Conventions… • We will use an underscore before the name of a variable that belongs to the class (as opposed to a local variable that belongs to a method): _hour _minute • This is “just” a Java convention, but stick to it, for everyone’s sake…

  21. The Time objects • The objects themselves, created from the Time class, can hold values for _hour and _minute Time bill _hour _minute Time addMinutes( int m ) void printTime( ) Attributes: _hour = 7 _minute = 18Methods: Time addMinutes(int m) void printTime ( ) scott Attributes: _hour = 14 _minute = 41Methods: Time addMinutes(int m) void printTime ( )

  22. The Time Class’s Interface • A method that adds m minutes to an existing Time object’s time, returning a new Time object with the new timeTime addMinutes(int m) • A method that prints the value of a Time objectvoid printTime( ) • A constructor, for creating and initializing a Time objectTime (int h, int m)

  23. Encapsulation • The internal state of an object is not directly accessible to other parts of theprogram • Other parts of the programcan only access the objectusing its interface • We say that the state isencapsulated or hidden • This gives modularityto the program addMinutes(int m) . . . . . . • _hour • _minute printTime()

  24. Encapsulation • Hiding what’s inside the object is a big part of Object Oriented Programming • Programming projects get complicated • You can only hold (7 plus or minus 2) facts at a time in your brain • Break the big problem into individual objects that each works as a “black box”

  25. Not Just a Pretty Interface • You are told to implement the Time class • Your boss tells you what the class’s interface is; there’s another group (in San Jose) that’s building the rest of the program, and they will use the Time class that you build • The details of what goes on inside the class are hidden • The important thing is: the San Jose group doesn’t need to know about the implementation of Time, only its interface!

  26. Clients and Classes • Methods that use the Time class are called clients of the class • To keep roles clear, both clients and classes have certain rights • This is a “division of labor”

  27. Rights of a Class • Define the public interface of the class • Hide any and all private details of implementation • Protect internal, private data from access by a client • To change the implementation details at any time, provided the public interface stays the same

  28. You Get to “Fine-Tune” the Encapsulation • The private modifier specifies an identifier that is only visible within the class. Usually used for fields (instance variables) of the class. • The public modifier specifies an identifier that is accessible to all other classes. Usually used for methods.

  29. Rights of a Client • To declare variables of the class type • To create instances (objects) of the class, using the class constructors • To send messages to instances of the class by invoking the instance methods defined by the class • To know the public interface of the class • To know which instance methods alter the instance

  30. The Structure of theTime Class Definition class Time{declarationspublic Time (int h, int m) {... }public Time addMinutes (int m) {... }public void printTime ( ) {... }} constructor definition method definition method definition

  31. API Documentation • Your classes are often intended to be used by other programmers • Programmers that use your class are not interested in the way it is implemented. They want to use it as a whole and are only interested in what it does and how to use it. • API (Application Programmer Interface) documentation is a description of the interface of the class intended for the application programmer who wants to use it. • To use the class, we need not (and should not) look at the code. All that is needed is the class API.

  32. API Documentation • The JDK contains a special tool for the generation of API documentation for your classes, called javadoc. • Any documentation which is part of the interface begins with /** (double asterisk) and ends with */ • javadoc takes as input Java programs and automatically generates documentation using: • the public/protected method signatures • the documentation comments (enclosed by /** … */). • The output is an HTML file which can be viewed by an internet browser.

  33. class Clock API Documentation /** * A clock represents a point of time in a 12 * hour period within a precision of seconds. * Its range: 1:00:00 -- 12:59:59. */ public class Clock { private int _hours; private int _minutes; private int _seconds; /** * Constructs a Clock: Sets the clock to the * specified time. */ publicClock(int hours, int minutes, int seconds){ //… }

  34. Clock API Documentation – continued /** * Constructs a Clock: Sets the clock to 12:00:00 */ publicClock(){ this(12,0,0); } /** * Advances this clock by 1 second. */ public void secondElapsed() { //… } //…

  35. Javadoc Process javadoc .javafile .htmlfile View using a browser

  36. Clock javadoc – page 1

  37. Clock javadoc – page 2

  38. What should you comment? • You should put a documentation comment for the class itself and for any member of the class which is part of its interface • All public constructors and methods should have documentation comments • Private methods are not part of the interface of the class, thus javadoc skips them. (But you should still comment them for internal purposes.) • In the rare cases that there are public fields, they should have documentation comments

  39. API Documentation • Remember that documentation comments are written for programmers who use your class as a whole. They should describe only • What the class does; • How to use it. • Documentation comments should not describe how a class is implemented. • Documentation comments should be • Short and descriptive; • Written in a simple language (ENGLISH); • Accurate. • Assume that the reader doesn’t know anything about your class

  40. API Documentation Tags • Documentation comments can also include tagged paragraphs that give a standard way to document several features of the interface such as method parameters, return values, etc. • A tagged paragraph begins with the symbol @ followed with a tag keywords. Tags: @see, @author, @version, @param, @return, @exception. • Documentation comments text can include HTML tags.

  41. @param tag /** * Changes the current time to hour:minute:second * @param hours The new hour value. * @param minutes The new minutes value. * @param seconds The new seconds value. */ public void setTime(int hours, int minutes, int seconds) { this.hours = hours; this.minutes = minutes; this.seconds = seconds; }

  42. setTime generated javadoc

  43. @return /** * Returns the current hour * @return The current hour (between 1 and 12). */ public void getHour() { returnhours; }

  44. getHour javadoc

  45. Naming • The names you use for your class and for its public methods are part of the class API • Good descriptive naming is crucial for a clear API • General rules about naming: • Follow the Java conventions • Use descriptive names • Do not use abbreviations! • Make names long enough, but not unnecessarily long • Consists of words in English with no abbreviations • Use a dictionary • Read the style guidelines!

  46. The Structure of theTime Class Definition class Time{declarationspublic Time (int h, int m) {... }public Time addMinutes (int m) {... }public void printTime ( ) {... }} constructor definition method definition method definition

  47. Creating a Time Object As you know:Time dawn; dawn = new Time(5, 35);or, all at once,Time dawn = new Time(5, 35); declaration creation and assignment

  48. What’s Really Happening? • When we declare a variable of a simple type, we actually get a location in memory to store the value:int temperature;gives us: temperature

  49. What’s Really Happening? • When we declare a variable of an object type, we get a reference in memory to an object (the object’s address); the object is stored elsewhere:Time dawn = new Time(5, 35);gives us: dawn Attributes: _hour = 5 _minute = 35Methods: Time addMinutes(int m) void printTime ( ) dawn the heap

  50. What’s Happening Behind the Scenes? • We just talked about object variables and how they “point” to an object in the heap • Let’s look at what’s going on in the computer’s memory, behind the scenes • You don’t handle this yourselves, Java does. But it helps (e.g., understanding parameter passing) if you understand what is going on

More Related