27
CS2110: Software Development Methods • Readings: PDF on website: 1 st edition of MSD text, Appendix A. This covers: • Structure of Java program; data types; expressions; assignment; conditionals; loops; methods Section 3.2 in 2 nd edition of MSD text • Creating classes Java Software Review #1 Fall 2010, © Tom Horton

CS2110: Software Development Methods Readings: PDF on website: 1 st edition of MSD text, Appendix A. This covers: Structure of Java program; data types;

Embed Size (px)

Citation preview

CS2110: Software Development Methods

• Readings:• PDF on website: 1st edition of MSD

text,Appendix A. This covers:

• Structure of Java program; data types; expressions; assignment; conditionals; loops; methods

• Section 3.2 in 2nd edition of MSD text• Creating classes

Java Software Review #1

Fall 2010, © Tom Horton

Goal for these slides, lecture

• This will not be a “re-lecture” of what things you learned earlier• Some of you remember it well• You'll should be able to remember or re-

capture it• Read your book(s)!• Do some programming

• Use Javabat• But also download Java and an IDE (DrJava etc.)

• Ask questions!• By email, in office hours, in lecture or lab

Some Important Java Principles

1. Class concepts and terminology2. Program Structure3. Primitive Types vs. Reference Types

• equals() vs ==

4. Arrays, Vectors, and ArrayLists5. Some conventions and style guidelines

Classes in OO

• Objects and variables are “things” in a running program that contain data• x, y, myName, System.out

• Variables have a type• x and y are both whole numbers• myName is a string of characters

• Primitive types: int, double, boolean• A class is also a type!

• More complex than primitive types• We define our own. Or, defined in class

libraries.

Class Terminology

• Classes define a new kind of objects• Create objects themselves with “new”

• Classes allow us to encapsulate data inside an object• Java term: field (AKA attribute, instance

variable,…)• anObject.id

• Classes allows us to “bind” functionality to objects of that type:• Java term: method (AKA member function,

operations)• anObject.equals(obj2)

Class Terminology

• Accessibility• Controlling what other objects or other parts of

a program can access a given object's fields and methods

• Modifiers on definitions:• public, private, protected, “package”

• Can be applied to:• entire class• a given field• a given method

• Read about the basics of this!

2. Java Program Structure

• How do we think of a Java program?• A collection of classes• One has a method main()

• To run a program• .java files compiled into .class files• Invoke Java and tell it the .class file to run

main() in

• Beyond the basics:• You can use other classes that you don't write• Libraries, classpath, jar files,…

Class Structure

• Inside a class• Field declarations• Method declarations

• Constructors• Other methods

• Remember:• Don't nest methods• One class per file (for now)

3. Primitive Types vs. Reference Types

• Primitive type (Built-in to Java)• A “box” or chunk of memory holding the data

itself

• Reference types• All objects defined from classes• The object “refers to” or “points to” the chunk of

memory that actually holds the data• Object vs. object-reference vs. object-variable• An object-variable must be made to refer to a

chunk• Create chunks with new (which calls a constructor)• Use assignment• null value for an object-variable: not pointing to anything

• Example: MyClass obj1 = new MyClass();• Draw this as a picture!

Identity, Equality of Objects

• Two object-variables can refer to the same object: MyClass obj1 = new MyClass(); MyClass obj2 = obj1;

• Two references, one chunk of data• Think of as two names for one thing

• Is obj1==obj2? Sure!• They reference the same object

• Not always what we want!

Identity, Equality of Objects

• Consider: MyClass obj1 = new MyClass(“Bob”); MyClass obj2 = new MyClass(“Bob”);

• The goal here is to have two identical objects that would be equal

• Does obj1==obj2?• No! Object-variables reference two different

chunk of memory, two different objects

• Solution:• We define the following method in MyClass:

boolean equals(Object obj2) // why Object obj2?

• Use equals() not ==

Identifying Objects by a Key Value

• Often we have collections of objects stored somehow• Array, collection class (e.g. Vector), database

• Wish to search (or sort) this collection• How to identify the item we want?• Almost certainly not ==• Sometimes equals()• But often we rely on one field's value: a key

• Often equals is written to test just the object's key• Or sometimes we write some kind of “match” method

Method equals() in Java

• Every object has one! (More on how later)• Unless you write your own version, equals() is

defined to be same as ==• Not too useful usually for your classes

• Write your own: public boolean equals (Object obj2)

• Important: parameter must be of type Object• You must cast it inside your method to your own class• More on why later soon, but example is next

How to Write equals()

• In Java, there’s a standard convention for writing equals(). Follow it!

• Parameter must be of type Object• Check if it’s an instance of the current

class• If not same type, the two things are not equal,

right?• If so, cast to the current class and compare

fields as appropriate

Example of equals()

• Rational number: a/b equals c/d iff a*d == b*c

// in class Rationalpublic boolean equals(Object o) {

if (! (o instanceof RationalNumber) )return false;

// else cast o to be Rational object and testRationalNumber num2 = (RationalNumber) o;return (this.numerator * num2.denominator)

== (this.denominator * num2.numerator);

}

4. Lists of Things in Java

• Several ways to store a sequence of items• Arrays – built into Java, as are primitive types

• But really are a class

• Vector class (“old” but now almost like ArrayList)• Collections class, like ArrayList (coming soon!)

• Arrays• The type defined like this: AnyType[] array-ref• This is a reference variable (just like an object

ref)• So must use new to create the array itself

int[] myList = new int[5];

• How many? myList.length (a field)• Indexing: myList[0] … myList[4]

Arrays vs. Collection Classes

• Arrays have an important limitation: fixed size

• OO languages have collection classes that store objects in various ways• Almost always includes something like an array• What do you think the advantages might be?

• Vector: from original version of Java• ArrayList: part of the standard family of

collection classes• Vectors have been upgraded to be almost the

same as ArrayLists (more later). We'll use ArrayLists in this class. You can use Vectors.

• (Difference? Vectors better when >1 thread)

ArrayLists vs Arrays

• In general: Prefer ArrayLists to arrays.• Note #1: Again, Vector like ArrayList

• Arrays more efficient. (But do you really care?)

• Arrays OK if• You know in advance how large it will be• You plan on handling “holes”, i.e. elements that

don't hold actual data

• See slides on ArrayLists

More on Arrays

• Question: Draw a picture that shows the difference between:

int[] array1;int[] array2 = new int[0];

• What would the first declaration be good for?What would the second declaration be good for?

• Answers:• The first could reference one array object,

created elsewhere. What it references could be changed!

• The second – not really very useful!

Processing Arrays (reminders)

• We use the length field frequently• Don't forget: it tells how many items the array

can hold, i.e. its capacity• The items are stored from index 0 to length-1

• So, a very common idiom is: for (int i=0; i < array1.length; ++i) {

// do something with array1[i]}

• What happens if you use an invalid index?• Answer: an exception is thrown (one you can

catch).• It's the ArrayIndexOutOfBoundsException

exception

“For Each” Statement

• From the last slide: a very common idiom is: for (int i=0; i < array1.length; ++i) {

// do something with array1[i]}

• Since Java 1.5, a simpler way of doing this:define local-to-loop variable to hold next element for (int value : array1 ) { // do something with value }

• Note: you have no access to the index (what was variable i)

Getting Data into Arrays

• Can use an initializer: int[] intArray = { 1, 2, 3+4, 5-6, 8 };• note that int expressions are allowed

• Or, we use a loop like the last slide• Or, some methods in class libraries return

arrays• See the String.split() method, for example

• Remember: if anArray is an array of some type, then element anArray[i] is one object (or variable) of that type and so anything legal for one object of that type is legal for anArray[i]

What's Initially in Arrays

• For this:int[] intList = new int[10];

what's the initial value of intList[0]? intList[9]?• Answer: follows rules for how primitive types are

initialized

• For this:String[] strList = new String[10]

what are the initial values of the array elements?• Answer: they have value null

• Be careful with this! Easy to think you have a set of String objects. You only have references that could be made to refer to String objects.

Exercise

• Could you write a simple class that encapsulates an array of information: class GradeList

• Field(s):• grades: array of doubles

• Methods:• Constructor (with size)

• What about a default constructor? What should it do?

• double getMax()• double getGrade(i)• void setGrade(i, newGradeVal)• void removeZeros()

• is this possible?

Comments on GradeList example

• Default constructor could only be defined arbitrarily• The field will be: double[] grades;• Need to allocate an array-object of some fixed

size• Need to know how big it must be. Can't make it

grow later.

Another Comment on GradeList example

• removeZeros()• Yes, we can change elements in the array.

We an “move down” positive values to “remove” zeros

• But, what about space at the end? What goes there?

• We can't shrink the array! Put zero's there as placeholders? (Ugh!)

• One option:• new class field, size, to record how many “real”

data-items are in the array• When processing, only loop from 0 to size-1• size must always be <= array's length field

5. Some Conventions and Guidelines

• Class names start with upper-case and are mixed-case: MyFirstClass

• object names start with lower-case and are mixed-case: aStringObject

• Constants (declared final) are all upper-case with underscores: MAX_SIZE

• How to name fields?• Some use underscores: _id or id_• Some prefix: thisId or m_Id• But not us! Just like object-name: id