CPS122 Lecture: Introduction to Java

Similar documents
CPS122 Lecture: Defining a Class

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CPS122 Lecture: From Python to Java

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

CS112 Lecture: Defining Instantiable Classes

CS112 Lecture: Primitive Types, Operators, Strings

CS112 Lecture: Working with Numbers

CPS122 Lecture: Course Intro; Introduction to Object-Orientation

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Full file at

Objectives: 1. Introduce the course. 2. Define programming 3. Introduce fundamental concepts of OO: object, class

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Type Checking and Type Equality

Chapter 1 Getting Started

6.001 Notes: Section 6.1

Software Design and Analysis for Engineers

3. Simple Types, Variables, and Constants

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

1. BlueJ bank example with subclasses of BankAccount 2. Transparency of UML diagram for BankAccount class hierarchy

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

CPS122 Lecture: Detailed Design and Implementation

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

SOFTWARE ENGINEERING Prof.N.L.Sarda Computer Science & Engineering IIT Bombay. Lecture #10 Process Modelling DFD, Function Decomp (Part 2)

CS 1302 Chapter 9 (Review) Object & Classes

High Performance Computing Prof. Matthew Jacob Department of Computer Science and Automation Indian Institute of Science, Bangalore


CSCI 2101 Java Style Guide

Types and Static Type Checking (Introducing Micro-Haskell)

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

Key Differences Between Python and Java

Defensive Programming

CS 142 Style Guide Grading and Details

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute

CSE 341, Autumn 2015, Ruby Introduction Summary

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

ECE 122. Engineering Problem Solving with Java

Maciej Sobieraj. Lecture 1

The development of a CreditCard class

Intro. Scheme Basics. scm> 5 5. scm>

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

VARIABLES AND TYPES CITS1001

Defining Classes. Chap 1 introduced many concepts informally, in this chapter we will be more formal in defining

CS 231 Data Structures and Algorithms, Fall 2016

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

UNDERSTANDING CLASS DEFINITIONS CITS1001

Types and Static Type Checking (Introducing Micro-Haskell)

These are notes for the third lecture; if statements and loops.

Lesson 1A - First Java Program HELLO WORLD With DEBUGGING examples. By John B. Owen All rights reserved 2011, revised 2015

Bits, Words, and Integers

6.001 Notes: Section 8.1

Variables. Data Types.

Variables and Constants

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

EC121 Mathematical Techniques A Revision Notes

STUDENT LESSON A5 Designing and Using Classes

Course Outline. Introduction to java

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Introduction Welcome! Before you start Course Assessments The course at a glance How to pass M257

Software Design and Analysis for Engineers

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

printf( Please enter another number: ); scanf( %d, &num2);

Week - 01 Lecture - 04 Downloading and installing Python

Ticket Machine Project(s)

Typing Data. Chapter Recursive Types Declaring Recursive Types

Chapter 2 Working with Data Types and Operators

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Programming Lecture 3

Java Bytecode (binary file)

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Basic Programming Language Syntax

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing

Binary, Hexadecimal and Octal number system

6.001 Notes: Section 1.1

3 ADT Implementation in Java

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

CS112 Lecture: Loops

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

2.2 Syntax Definition

CS211 Lecture: Design Quality; Cohesion and Coupling; Packages

Floating Point. What can be represented in N bits? 0 to 2N-1. 9,349,398,989,787,762,244,859,087, x 1067

Students received individual feedback throughout year on assignments.

CIS 110: Introduction to Computer Programming

Contents. Slide Set 1. About these slides. Outline of Slide Set 1. Typographical conventions: Italics. Typographical conventions. About these slides

Chapter 4 Defining Classes I

Visual C# Instructor s Manual Table of Contents

Agenda: Notes on Chapter 3. Create a class with constructors and methods.

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Lecture Set 2: Starting Java

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

MAT128A: Numerical Analysis Lecture Two: Finite Precision Arithmetic

CS102: Variables and Expressions

Transcription:

CPS122 Lecture: Introduction to Java last revised 10/5/10 Objectives: 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3. To introduce a few of the key syntactic differences between Python and Java 4. To introduce structure of a Java class 5. To introduce the different kinds of Java variables (instance, class, parameter, local) Materials: 1. Projectable showing difference between static and dynamic typing 2. Python interpreter and Dr. Java for demos 3. Projectable showing different syntax for control structures 4. Features that can occur in a class handout I. Introduction A. As you may recall, in our course introduction we noted that this class will use Java as a programming language, rather than Python, for three reasons, all related to the size of the problem we are seeing to solve. Do you recall what those reasons where? ASK 1. Java is a compiled language. 2. Java is a statically-typed language. 3. Java is designed for an approach to software development known as object orientation. B. We talked a bit about the latter in the first lecture, and will say a lot more about it throughout the course. In this lecture, we will explain the first two, and also say a bit more about Java syntax. II. Compilation versus Interpretation A. Computer hardware (a CPU chip) is capable of interpreting programs written in binary machine language - 1's and 0's, 1. However, writing programs in machine language has lots of disadvantages: 1

a) It is tedious. b) It is error-prone. c) Correcting such programs when errors are found is extremely difficult. d) Modifying such programs is extremely difficult. e) Perhaps most important of all, the machine language of each family of CPU chips is unique to that family. Thus, a program written for one family of chips (e.g. the Intel 80x86 used on many current systems) is totally useless for some other family. 2. For this reason, very early in the history of computer science, various higher-level programming languages were developed. Though still not as natural as English, they are a whole lot simpler to use than binary machine language. Python is one such language; Java is another; and there are hundreds more. In addition to being much easier to use, higher level languages have the advantage of being designed to be cross-platform - i.e. the same program should be capable of being used on multiple families of CPU. B. With the use of higher-level languages, a new problem arises. The CPU can only interpret its binary machine language - so how does it execute a program written in a higher-level language? Two approaches to solving this problem have been widely used. 1. Software interpretation. A special program called an interpreter is written for a particular chip, in the binary machine language of that chip. This program reads the higher-level language program one step at a time and interprets and carries out that step. 2. Compilation. A special program, called a compiler, is used to translate the higher-level language program into the binary machine language of the target system 3. The key difference between the approaches is how often a given higher-level language statement is understood. With an interpreter, it is understood each time it is executed. With a 2

compiler, it is understood once, and then translated, as a separate step before it is executed. Example: Say to a student who knows German: Heben sie die hand, bitte ( Raise your hand, please ) Ask the same student to translate into English, hand the translation to another student to interpret. 4. Often, one approach or the other is the preferred approach for a given higher-level language. For example, Python is designed to be implemented using software interpretation, and Java - like most higher-level languages - is designed to be implemented using compilation. [ There are a few languages that can actually be implemented either way. ] C. A key visible distinction between the two implementation models is that with a compiled implementation there is a distinct compilation step that occurs between writing a program and running it, whereas with an interpreted implementation it is possible to enter a single statement and have it executed immediately. 1. Of course, the interpreted approach is more convenient to use. 2. However, though the compiled approach requires extra effort, it has a number of advantages. a) A compiled program can perform the same task much faster than an interpreted program, because the step of understanding the source program is done just once, at compile time, and because it is possible to perform some optimizations during translation that make the program run more quickly. (1) This is not much of an issue in many cases, given the speed of modern computers. But it can be an issue with compute-intensive applications, such as certain kinds of media operations (e.g. movie, sound or picture editing) or scientific number-crunching. 3

(2) Some interpreted implementations mitigate the problem by storing the program internally in a partially-translated form to avoid doing all the work of understanding the source each time a statement is executed, and may even save the translated form to facilitate subsequent loading. (For example, Python does this with its.pyc files). But this still doesn t yield the kind of efficiency possible with a compiled implementation. b) A more significant issue is software reliability. A compiler can be designed to catch many kinds of errors (but by no means all) when a program is compiled, rather than having them show up when the program is running. (1) We will see lots of examples of this as we learn Java. (2) There will be times when you will be tempted to think of detection of errors by the compiler as a nuisance, but remember this is much less of a nuisance than having something go wrong when the program is running! c) Compiled implementations also have significant security advantages. D. Having said all this, for demonstration purposes we will make use from time to time of a program known as Dr. Java. This has an interaction window which allows you to enter a Java statement and have it executed immediately - just like in an interpreted language. But what is really happening is that Dr. Java is compiling a miniprogram containing the statement behind the scenes. III. Static versus Dynamic Typing A. Before we discuss the issue of static versus dynamic typing, we need to first introduce the notion of a data type. Both Python and Java (and indeed almost all programming languages) have this concept. 1. A data type defines a set of possible values and a set of possible operations. For example, most programming languages (including Python and Java) have the notion of the data type integer (called int in both languages). a) The possible values of an int are the mathematical integers (actually a finite subset in Java). 4

b) The possible operations on an int are the standard arithmetic operations such as +, -, *, / etc. 2. Most programming languages (including Python and Java) are strongly-typed languages - which basically means that one cannot apply an operation to a data item for which it is not appropriate. Example: DEMO in Python 4-3 is OK "four" - "three" is not - the type of the values is string, not integer 3. In fact, sometimes the same symbol may specify a different operation depending on the types of the items it is applied to Example: DEMO in Python 4+3 - here + is arithmetic addition "four" + "three" - here + is string concatenation B. To illustrate the difference between static and dynamic typing, consider the following task: calculate the two roots of a quadratic equation using the quadratic formula you learned in high school: If an equation is of the form Ax2 + Bx + C = 0, then its roots are x = -B +/- sqrt(b2-4ac) PROJECT TypeDeclarations projectable (Note: these are just exerpts from complete programs, written so as to use a similar style insofar as possible. For simplicity we assume we will only use them for cases having two real roots.). What differences do you see? ASK - Be sure they see the explicit declarations of the variables 1. In the Java program, the variables a, b, c, x1, and x2 are explicitly declared to be of a data type known as double (double-precision real numbers) before they are actually used. 2. In the Python program, these variables are first introduced when they are used. 5

3. The difference arises because Java is statically typed, which means three things: a) A variable must be explicitly declared to be of some type before it can be used. b) A variable must only be used in a way that is appropriate for its type. c) The type of a variable cannot be changed once it is declared to be of a certain type. DEMO with Dr. Java: int x String x 4. In contrast, Python is dynamically typed. a) Variables are not explicitly declared. Rather the type of a variable is based on the value it currently holds. b) Though a variable can only be used in a way that is appropriate for its current type, the type of a variable can be changed by giving it a different value. DEMO a = "four" a - 1 a = 4 a - 1 5. Although declaring a variable and giving it a value are conceptually two different things, Java does allow these two operations to be combined into a single statement. Example: int x; x = 3; is equivalent to int x = 3; C. At first glance, it may appear that static typing is a nuisance. However, it has several very significant advantages 6

1. It provides some protection against typographical errors. Example: suppose you used a variable named something in a program, and at one point misspelled it as sonething in an assignment statement sonething = 4 The Python interpreter would allow this, by treating it as the definition of a new variable - which could result a hard-to-find error when the variable something turns out to have the wrong value elsewhere in the program. In contrast, the Java compiler would flag this as an unknown symbol. 2. It provides protection against inadvertent misuse of a variable. The compiler can (and does) check each use of a variable to be sure that the use is consistent with its declared type. Example: if the variable a were declared as a string, the Java compiler would flag a - 1 as an error DEMO with Dr. Java String a a - 1 3. It facilitates production of more efficient code. With a dynamically typed language, each time a variable is used its current type must be checked to determine whether the operation is appropriate and, if so, what it means. With a statically typed language, all this is checked at compile time. D. Java has 8 builtin types known as primitive types that have a special status in the language. and are represented in an efficient way in memory. (If you are familiar with the C programming language, these are similar to the primitive types of C.) 1. Four different types of integers - distinguished by the number of bits of memory used to store each, and by the resultant range of possible values. a) byte - one byte (8 bits) - range of values -128.. 127 b) short - two bytes (16 bits) - range of values -32768.. 32767 7

c) int - four bytes (32 bits) - range of values -2,147,483,648.. 2,147,483,647 d) long - eight bytes (64 bits) - -9,223,372,036,854,775,808.. - 9,223,372,036,854,775,807 e) Unless there is a good reason for doing otherwise, int is typically the one that is used 2. Two different types of real numbers - distinguished by the number of bits of memory used to store each, and by the resultant precision and range of possible values a) float: 4 bytes (32 bits). Precision equivalent to about 7 decimal digits, with range of values on the order of ± 1038 b) double: 8 bytes (64 bits): Precision equivalent to almost 16 decimal digits, with range of values on the order of ± 10308 c) Unless there is a good reason for doing otherwise, double is typically the one that is used 3. A character type (char) that holds the code for a single character. 4. A boolean type whose possible values are true and false. E. Java also makes it possible to define new data types by defining classes (which we will talk about shortly), arrays (which we will also talk about in this series of lectures) or interfaces (which we will not discuss until much later in the course.) The code for defining such a new type is, itself, written in Java. Collectively, these types are called reference types. 1. A large number of reference types are defined as part of the standard Java libraries. We will make use of a number of these throughout the course. 2. One such type is that used for character strings (String). It is not a primitive type because Strings can vary widely in the amount of storage required. It does, however, have a privileged status when compared to other refernce types. 3. The process of creating a Java program centers around creating new classes, each of which, in effect defines a new data type. 8

F. Thus, in Java, every data type is either one of the 8 primitive types or it is a reference type defined by code written in Java. A variable can be declared to be of any of these types. IV. Key Syntactic Differences between Java and Python A. As you probably noted in the excerpts I projected earlier, there are quite a number of syntactic differences between Java and Python. Most of these will come to the surface as we encounter them, but there are a few worth mentioning now. B. Delimiting individual statements 1. In Python, a statement runs until the end of a line, though it is possible to extend statements over multiple lines by ending each line except the last with a '\'. It is not possible to have two statements appear on the same liine 2. In Java, statements are terminated by a semicolon. A statement can be spead over multiple lines, and multiple statements can appear on one line. DEMO with Dr. Java int a = 3; int b = 4; int c = a + b; System.out.println(c); C. Comments 1. In Python, a comment is started by a # and extends to the end of the line 2. In Java, there are two ways of marking comments a) If a // occurs, everything following it - to the end of the line - is a comment. (So // in Java behaves just like # in Python) b) If a /* occurs, everything following it - to the next occurrence of */ is considered a comment. This may be a part of a line, or may extend over several lines DEMO with Dr. Java 9

/* Short comment */ int d = 3; /* Long comment extending over multiple lines */ System.out.println(d); D. Conditional and Looping Statements 1. Both Python have the notion of a conditional statement introduced by the word if, and looping statements introduced by while or for, but the syntax is quite different. PROJECT comparison of syntax for control structures a) Python: keyword expression : b) Java: keyword ( expression ) 2. Delimiting the scope of conditional/looping statements a) In Python, the scope of a conditional/looping statement is delimited by indentation Example: if x == 0: print x is 0 b) In Java, the scope of a conditional/looping statement is delimited by braces. The Java equivalent would be if (x == 0) { System.out.println("x is 0"); } (1) Actually, if the scope of a conditional/looping statement is just a single statement, the braces are not needed Example: the above could be written if (x == 0) System.out.println("x is 0"); 10

(2) It is considered good practice to indent statements in a manner similar to the manner used in Python for readability, but the compiler pays attention to the braces - not indentation - so the following is equivalent, though stylistically poor: if (x == 0) System.out.println("x is 0"); (Indentation conventions for reasons of style preceeded Python; Python just adopted them and gave them syntactic significance) V. Objects and Classes in Java A. Review from first class 1. Recall that a program in an object-oriented language such as Java collection of interacting objects. An object is a software entity that typically models something in the real world and has three critical properties. a) State - the object encapsulates some information about itself, which are sometimes called its attributes. b) Behavior - the object can do some things on behalf of other objects c) Identity - the object is distinguishable from all other objects of the same general type. (The definition of an object in terms of state, behavior, and identity is a 3 AM phone call fact. ) 2. Each object in an object-oriented system belongs to some class. a) A class can be thought of as the set of all objects of the same kind - e.g. in the example we looked at in the first class, all the savings account objects together constitute the SavingsAccount class. b) The basic unit of a Java program is the class. In Java, everything must appear inside a class definition - there are no stand-alone statements or functions. 11

3. When we write OO programs in a language like Java, we define classes, and then use them as templates for constructing objects. Each individual object is called an instance of its class, and each object is an instance of exactly one class. Example: Recall the SavingsAccount example we looked at in the first lecture a) OPEN IN BLUEJ - Note two classes b) We will now take a look at the code for one of these classes: SavingsAccount HANDOUT: Features that Can Occur in a Class B. Each file should begin with a file/class comment - a comment (in English) that describes the purpose of the class and specifies its author and date. NOTE in handout Generally each class is in its own file. The name of the file will be the same as the name of the class - e.g. the example would appear in a file called SavingsAccount.java. (This is a requirement enforced by the java compiler). There is the possibility of defining a class inside another class - but we won t discuss that now.. C. Each class has a name. The name should be clearly related to the purpose of the class. D. The definition of a class is delimited by braces. (These are always required). E. A class generally has instance variables. 1. Each object that is an instance of a given class has its own copy of each instance variable. These variables exist as long as the object exists. 2. In general, each piece of information that an object needs to know will be represented by an an instance variable. NOTE instance variables accountnumber and currentbalance in handout. 12

Insofar as possible, the name of an instance variable should make its purpose crystal clear. In some cases, a supplementary comment may be desirable to add information not obvious from the name. (e.g. the comment on currentbalance that notes how it is represented.) 3. Further, each object will also need an instance variable to refer to each kind of other object that it knows. (I.e. the instance variables hold answers to two questions: what does this object know? and who does this object know?) There are two possibilities for these instance variables a) The instance variable may simply be a reference to some other object. NOTE in handout: Instance variable owner b) Or, the instance variable may be a special kind of object called a collection which holds references to several other objects of the same kind. EXAMPLE: Since bank accounts can have multiple owners (joint accounts), instead of an instance variable called owner, we might have one called the owners that is a collection. (Collections are a topic we will discuss later this semester - so far now we don t know how to do this in Java, so we ll stick with a single owner for this example.) 4. Instance variables always have a visibility specifier, which will be one of public, protected, private. a) We will discuss these later in the course - but for now you should simply use private. b) This relates to a key concept in OO called encapsulation - each object encapsulates within itself certain information that can only be accessed through its methods, and hence is not subject to surprise changes. 5. Conceptually, we decide on the instance variables for a class early in the process. In this example, they are placed at the beginning of the class. However, a case can also be made for listing the instance variables near the end of the class declaration. Either place is acceptable (but not strung out everywhere!) 13

F. A class generally has one or more instance methods (mutators and accessors) 1. In general, each thing an object needs to be able to do will be represented by an instance method. NOTE in handout 2. Methods are of two general types a) A mutator changes the state of the object. Examples: deposit(), withdraw(), calculateinterest() b) An accessor furnishes information about the state of the object Examples: reportbalance() and getaccountnumber() 3. A method may or may not have one or more parameters, which represent information flowing into the method from its caller. A parameter is specified in the method header and - like all variables in Java - is declared to be of a particular type. Examples: deposit() and withdraw() each have a single int parameter specifying the amount of money to be deposited or withdrawn. calculateinterest(), however, does not need a parameter Not shown in the handout is the possibility that a method might have more than one parameter. In fact, there is no limit on the number of parameters a method may have. 4. A method may or may not have a single return value, which represents information returned to the caller when the method is used. The type of the return value is specified before the method name; if there is no return value, void is used. Examples: deposit(), withdraw(), setannualinterestrate(), calculateinterest() do not have return values, but reportbalance() and getaccountnumber() do. The return value is a String in the case of reportbalance, int in the case of getaccountnumber(). 5. Can you see any relationship between the type of the return value and whether the method is an accessor or mutator? ASK 14

6. The body of a method is always delimited by braces, even if it is just one line. 7. An instance method is called by giving the object to which it is to be applied and the name of the method (together with its actual parameters), separated by a dot. Example:The constructor of SavingsAccount invokes the addaccount() method of its owner 8. A class method is called by giving the name of the class of which it is a part and the name of the method (together with its actual parameters), separated by a dot. Example: to change the interest rate for all SavingsAccounts to 3%, one would write SavingsAccount.setAnnualInterestRate(0.03); G. A class generally has one or more constructors. A constructor is similar to a method, but is used to initially create an object of the class. It's purpose is to put the instance variables in a correct initial state. 1. Two things distinguish a constructor from methods: a) The name of a constructor is always the same as the name of the class b) A constructor does not have a return type. Example: Show in handout 2. However, a constructor may - and generally does - have parameters which specify the information needed to initially create an object of the class. Example: the SavingsAccount() constructor has the Customer who owns the account as a parameter. It does not need a parameter for the account number, which the constructor itself assigns, nor for the initial balance, because this is always zero; 15

H. A class may also have class variables, constants, or methods. 1. A variable that holds a value that is shared by all the objects in the class can be declared as a class variable. NOTE in handout: two class variables. One is used to ensure that each account gets a unique number. The constructor uses this to assign a number to a newly-created account, and then adds one to it. Obviously, this must be shared by all instances of the class. Another is used to hold the interest rate, which is (in this case at least) is the same for all instances of the class. 2. A constant value that is the same for all objects in the class, and that either methods or clients of the class need to make use of can be declared as a class constant. NOTE in handout: many banks have a minimum balance allowed in account for paying interest. (An account with a balance below this amount is not eligible for interest.) Since this rule applies to all accounts, a class constant MINIMUM_BALANCE_FOR_INTEREST is used. (Constants use a special naming convention as here) (One might argue that this should also be a variable, so that the bank can change its rules. I made it a constant here so that I could illustrate both possibilities!) 3. A method that represents a responsibility of the entire class, not associated with any particular object in the class, can be declared as a class method. NOTE in handout: setinterestrate() method. 4. Instance methods can freely make use of class constants, variables, and methods; but that class methods cannot use instance variables or methods since they are not associated with any particular instance of the class. 5. Class variables, constants, and methods are distinguished from instance variables and methods by being declared static. 16

I. Note the use of comments throughout the class - a file/class prologue, method prologues, and prologues for public variables/constants. 1. In Java, the preferred way to do this is with a comment that goes immediately before the entity, begins with /**, and includes tags that begin with @. (The permitted tags depend on what type of comment you are writing - e.g. for a class comment tags like @author occur; for a method comment tags like @param occur.) 2. This style of comment is called a javadoc comment - and gets its name from a program (called javadoc) which automatically creates a set of documentation from code containing this style of comment. DEMO - Project documentation in Tools menu. Do for SavingsAccount and show result, walking through the javadoc relative to the handout for the code. VI. Variables and Constants A. We have now seen three different kinds of variables/constants. 1. What are they? ASK a) Instance variables b) Class variables c) Parameters 2. There is a fourth type of variable, known as a local variable, that pertains only to a single method. Example (from handout): result and cents in reportbalance() a) Such variables are usable only in the method in which they are declared, and only after the point at which they are declared (so a local variable declared in the middle of a method could not be used at the beginning.) b) They do not retain their values - and, in fact, cease to exist at all - between calls to the method 17

c) Parameters are like local variables in that they pertain only to the single method in which they are declared. 3. How do these different types of variable differ? ASK a) Each object belonging to a class has its own copy of each instance variable, that exists as long as the object exists. Example: any one of you can answer a question like what is your name? (Each of you has an instance variable called name) b) All objects belonging to a class share a single copy of each class variable. Example: all of you would give the same answer to the question how many credits does it take to graduate? c) Parameters and local variables exist only while a particular method is being executed. Example: If I were to ask you what are you eating? while you are sitting in Lane, you could give me an answer. But it would be silly for me to ask you that question while you are asleep, and probably offensive for me to ask you that question now! 4. Where are they declared? ASK a) Instance and class variables are declared outside any method - often at the start or end of a class. b) Parameters are declared in a method heading. c) Local variables are declared inside the body of a method. 5. The names of variables must be unique within their scope. a) A class may not have two instance or class variables with the same name. But two different classes can have instance/class variables with the same name. 18

b) A method may not have two parameters or local variables with the same name. But two different methods can have parameters/local variables with the same name. c) It is possible for a parameter or local variable of a method to have the same name as an instance or class variable of the class in which the method occurs. Example: the owner parameter of the SavingsAccount constructor has the same name as an instance variable of the SavingsAccount class. d) When this is done, the local declaration creates a hole in the scope of the instance/class declaration. (1) When the name occurs by itself, it is understood as referring to the parameter/local variable. Example: the second and third occurrences of owner (2) It is possible to refer to an instance variable by preceeding it with this. Example: the first occurrence of owner. Thus, this line says set the owner instance variable of the SavingsAccount being constructed to be equal to the value specified by the caller through the owner parameter. (3) A construct of this form is something of an idiom in constructors - the parameter specifying the initial value for the instance variable of the same name. Example: Note int Customer constructor B. Any variable can be given a value by an initializer when it is declared. 1. Example: nextaccountnumber in the SavingsAccount example 2. If an instance variable does not have an initializer, then it is initialized to a default value (e.g. 0 for numbers). 3. If a local variable does not have an initializer, it cannot be used until it is given a value by an assignment statement. 19

C. A constant is a special kind of variable that is given a value that cannot be changed. 1. Constants are declared using the word final. 2. Constants, of necessity, must be given a value by an initializer. 3. Constants are declared as class constants (static), since it makes little sense to think of different instances of a class as each having their own value of some constant!. 4. Constants typically are given names that consist of all uppercase letters, with underscores used to separate words (since mixed case is not used.) Example: MINIMUM_AMOUNT_FOR_INTEREST. D. It is also possible to have instance variables that are given an initial value, and then cannot be changed after that. 1. They are also declared using the word final. 2. Though they can be given a value by an initializer, they are typically given a value by a constructor. 3. They have a name that looks like any other variable name. Example: accountnumber - once given a value by the constructor, it cannot be changed. 20