using objects cs 101-e aaron bloomfield. announcements midterm 1 is a week from this wednesday...

43
Using Objects Using Objects CS 101-E CS 101-E Aaron Bloomfield Aaron Bloomfield

Post on 22-Dec-2015

214 views

Category:

Documents


1 download

TRANSCRIPT

Using ObjectsUsing Objects

CS 101-ECS 101-E

Aaron BloomfieldAaron Bloomfield

AnnouncementsAnnouncements

Midterm 1 is a week from this Midterm 1 is a week from this WednesdayWednesday

TESTS ARE IN CHM 402!!!!!!!!TESTS ARE IN CHM 402!!!!!!!! Schedule:Schedule:

This week: chapter 3This week: chapter 3 Next Monday: review for midtermNext Monday: review for midterm

Bring in questions!!!!Bring in questions!!!!

Homework done via CodeLabHomework done via CodeLab Use code VIRGIN-7592-1043Use code VIRGIN-7592-1043

There is a lab due this weekThere is a lab due this week

Warn your grandparents!Warn your grandparents!

Historically, this class has been Historically, this class has been lethal to grandparents of students in lethal to grandparents of students in the classthe class More often grandmothersMore often grandmothers

This happens most around test timeThis happens most around test time Although occasionally around the times Although occasionally around the times

a big assignment is duea big assignment is due

What is a referenceWhat is a reference

References are like pointers in C/C+References are like pointers in C/C+++ But they are not the exact same thing!But they are not the exact same thing! C++ has references also (in addition to C++ has references also (in addition to

pointers)pointers)

A reference is a memory addressA reference is a memory address

References 1References 1

Consider:Consider:int j = 5;int j = 5;

String s = “Hello world”;String s = “Hello world”;

Java translates that last line into:Java translates that last line into:String s = new String (“Hello world”);String s = new String (“Hello world”);

Note that there is no “new” here

References 2References 2

What’s happening in memoryWhat’s happening in memory

Primitive types are never references; Primitive types are never references; only objectsonly objects

5

int j

Hello world

String sTakes up 32 bits(4 bytes) of memory

Takes up 32 bits(4 bytes) of memory

Takes up 12 bytes of memory

References 3References 3

Consider our Circle classConsider our Circle classCircle c = new Circle();Circle c = new Circle();

radius = 1.0

Pi = 3.1415926536

Circle c

0x0d4fe1a8

At memory location 0x0d4fe1a8

Declares a reference to a Circle object

Creates a new Circle object in memory;Returns a reference to it

Circle c1 = new Circle();Circle c1 = new Circle();

Circle c2 = new Circle();Circle c2 = new Circle();

c1.radius = 5;c1.radius = 5;

c2 = c1;c2 = c1;

c2.radius = 7;c2.radius = 7;

System.out.println (c1.radius);System.out.println (c1.radius);

Consider:Consider:Circle c1 = new Circle();Circle c1 = new Circle();

Circle c2 = new Circle();Circle c2 = new Circle();

c1.radius = 5;c1.radius = 5;

c2 = c1;c2 = c1;

c2.radius = 7;c2.radius = 7;

System.out.println (c1.radius);System.out.println (c1.radius);

Pi = 3.1415926536

radius = 7.0radius = 1.0radius = 5.0

References 4References 4

Circle c1

Circle c2

radius = 1.0

Pi = 3.1415926536

What happensto this?

Java’s garbage collectionJava’s garbage collection

If an object in memory does not have If an object in memory does not have a reference pointing to it, Java will a reference pointing to it, Java will automagically delete the objectautomagically delete the object

This is This is really cool!really cool!

In C/C++, you had to do this by In C/C++, you had to do this by yourselfyourself

References and memoryReferences and memory Most modern computers are 32-bit computersMost modern computers are 32-bit computers

This means that a reference takes up 32 bitsThis means that a reference takes up 32 bits 2232 32 = 4 Gb= 4 Gb

This means that a 32-bit machine cannot This means that a 32-bit machine cannot access more than 4 Gb of memory!access more than 4 Gb of memory! Well, without doing some “tricks”, at leastWell, without doing some “tricks”, at least Most machines come with 1 Gb memory these daysMost machines come with 1 Gb memory these days Will come with 4 Gb in a year or soWill come with 4 Gb in a year or so

64-bit machines will have 16 exabytes of 64-bit machines will have 16 exabytes of memorymemory Giga, Tera, Peta, ExaGiga, Tera, Peta, Exa That’s 16 billion Gb!That’s 16 billion Gb!

The The nullnull reference reference

Sometimes you want a reference to Sometimes you want a reference to point to nothingpoint to nothing

Use the null reference:Use the null reference:Circle c = null;Circle c = null;

The null reference is equivalent to a The null reference is equivalent to a memory address of zero (0x00000000)memory address of zero (0x00000000) No user program can exist thereNo user program can exist there

The The nullnull reference reference

Consider:Consider:Circle c = null;Circle c = null;

c.radius = 0.0;c.radius = 0.0;

What happens?What happens?

What happens in What happens in Windows…Windows…

The The nullnull reference reference

Consider:Consider:Circle c = null;Circle c = null;c.radius = 0.0;c.radius = 0.0;

This is called accessing (or following) This is called accessing (or following) a null pointer/referencea null pointer/reference

What happens?What happens? Java: java.lang.NullPointerExceptionJava: java.lang.NullPointerException C/C++: Segmentation fault (core C/C++: Segmentation fault (core

dumped)dumped)

So what is a So what is a nullnull reference reference good for?good for?

Let’s say you had a method that Let’s say you had a method that returned a Circle when passed some returned a Circle when passed some parametersparameters Normally it returns a valid CircleNormally it returns a valid Circle

But what if it can’t? How to deal But what if it can’t? How to deal with that?with that?

Return a Return a nullnull reference reference

A bit of humor…A bit of humor…

Variable initializationVariable initialization Recall that Java will NOT initialize a variable Recall that Java will NOT initialize a variable

in a methodin a method But it does initialize a field of a classBut it does initialize a field of a class

Consider:Consider:String s;String s;

If s is a variable in a method, it is not If s is a variable in a method, it is not initializedinitialized

If s is a field in a class, it is initialized to nullIf s is a field in a class, it is initialized to null

Save yourself the hassle, and always Save yourself the hassle, and always initialize your variables and fieldsinitialize your variables and fields

Getting classyGetting classy

Your current jobYour current job Gain experience creating and Gain experience creating and

manipulating objects from the standard manipulating objects from the standard Java typesJava types

WhyWhy Prepares you for defining your own Prepares you for defining your own

classes and creating and manipulating classes and creating and manipulating the objects of those classesthe objects of those classes

Values versus objectsValues versus objects

NumbersNumbers Have values but they do Have values but they do notnot have behaviors have behaviors

ObjectsObjects Have attributes (fields) and behaviors (methods)Have attributes (fields) and behaviors (methods)

System.inSystem.in References an InputStreamReferences an InputStream

Attribute: keyboardAttribute: keyboard Behaviors: readingBehaviors: reading

System.outSystem.out References an OutputStreamReferences an OutputStream

Attribute: monitorAttribute: monitor Behaviors: printingBehaviors: printing

Other Java object typesOther Java object types

StringString

RectangleRectangle

ColorColor

JFrameJFrame

ConsiderConsider

StatementsStatementsint peasPerPod = 8;int peasPerPod = 8;

String message = "Don't look behind the String message = "Don't look behind the door!“door!“

How do we represent these How do we represent these definitions according to the notions definitions according to the notions of Java?of Java?

A bit of humor…A bit of humor…

8

message

peasPerPod

The value of Stringvariable messageis a reference to a

String objectrepresenting thecharacter string"Don't look behind

the door!"

The value of primitive intvariable peasPerPod is 8

+ length() : int+ charAt(int i) : char+ subString(int m, int n) String+ indexOf(String s, int m) : int+ ...

String

- text = "Don't look behind the door!"- length = 27- ...

RepresentationRepresentation

Shorthand Shorthand representationrepresentation

8

message

peasPerPod

"Don't look behind the door!"

ExamplesExamples

ConsiderConsiderString a = "excellence“;String a = "excellence“;

String b = a;String b = a;

What is the representation?What is the representation?

"excellence"a

b

Uninitialized versus nullUninitialized versus null

Consider (in a method):Consider (in a method):String dayOfWeek;String dayOfWeek;

Scanner inStream;Scanner inStream;

What is the representation?What is the representation?

-dayOfWeek

-inStream

Uninitialized versus nullUninitialized versus null

Consider (in a class):Consider (in a class):String dayOfWeek;String dayOfWeek;

Scanner inStream;Scanner inStream;

What is the representation?What is the representation?

nulldayOfWeek

nullinStream

Uninitialized versus nullUninitialized versus null

ConsiderConsiderString fontName = null;String fontName = null;

Scanner fileStream = null;Scanner fileStream = null;

What is the representation?What is the representation?

nullfontName

nullfileStream

AssignmentAssignment

ConsiderConsiderString word1 = "luminous";String word1 = "luminous";

String word2 = "graceful";String word2 = "graceful";

word1 = word2;word1 = word2;

Initial representationInitial representation"luminous"word1

"graceful"word2

word1

"graceful"word2

Using objectsUsing objects

ConsiderConsiderScanner stdin = new Scanner(System.in);Scanner stdin = new Scanner(System.in);

System.out.print("Enter your account name: ");System.out.print("Enter your account name: ");

String response = stdin.nextLine();String response = stdin.nextLine();

Suppose the user interaction isSuppose the user interaction isEnter your account name: Enter your account name: artisteartiste

"artiste"reponse

Scannerstdin

A bit of humor…A bit of humor…

String representationString representation ConsiderConsider

String alphabet = String alphabet = "abcdefghijklmnopqrstuvwxyz";"abcdefghijklmnopqrstuvwxyz";

Standard shorthand representationStandard shorthand representation

Truer representationTruer representationalphabet

a b c d e f g h i j k l m n o p q r s t u v w y z

"abcdefghijklmnopqrstuvwxyz"alphabet

String representationString representation ConsiderConsider

String alphabet = String alphabet = "abcdefghijklmnopqrstuvwxyz";"abcdefghijklmnopqrstuvwxyz";

char c1 = alphabet.charAt(9);char c1 = alphabet.charAt(9); char c2 = alphabet.charAt(15);char c2 = alphabet.charAt(15); char c3 = alphabet.charAt(2);char c3 = alphabet.charAt(2);

What are the values of c1, c2, and What are the values of c1, c2, and c3? Why?c3? Why?'j'c1

'p'c2

'c'c3

Program Program WordLength.javaWordLength.java

public class WordLength {public class WordLength {

public static void main(String[] args) {public static void main(String[] args) {Scanner stdin = new Scanner(System.in);Scanner stdin = new Scanner(System.in);

System.out.print("Enter a word: ");System.out.print("Enter a word: ");String word = String word = stdin.nextLinestdin.nextLine();();

int wordLength = word.length();int wordLength = word.length();

System.out.println("Word " System.out.println("Word " ++ word word ++ " has length " has length ""

+ wordLength + ".");+ wordLength + ".");}}

}}

More String methodsMore String methods

ConsiderConsiderString weddingDate = "August 21, 1976";String weddingDate = "August 21, 1976";

String month = weddingDate.substring(0, 6);String month = weddingDate.substring(0, 6);

System.out.println("Month is " + month + ".");System.out.println("Month is " + month + ".");

What is the output?What is the output?Month is August.Month is August.

More String methodsMore String methods ConsiderConsider

String fruit = "banana";String fruit = "banana";String searchString = "an";String searchString = "an";int n1 = fruit.indexOf(searchString, 0);int n1 = fruit.indexOf(searchString, 0);int n2 = fruit.indexOf(searchString, n1 + 1);int n2 = fruit.indexOf(searchString, n1 + 1);int n3 = fruit.indexOf(searchString, n2 + 1);int n3 = fruit.indexOf(searchString, n2 + 1);

System.out.println("First search: " + n1);System.out.println("First search: " + n1);System.out.println("Second search: " + n2);System.out.println("Second search: " + n2);System.out.println("Third search: " + n3);System.out.println("Third search: " + n3);

What is the output?What is the output?First search: 1First search: 1Second search: 3Second search: 3Third search: -1Third search: -1

More String methodsMore String methods ConsiderConsider

int v1 = -12;int v1 = -12;double v2 = 3.14;double v2 = 3.14;char v3 = 'a';char v3 = 'a';String s1 = String.valueOf(v1);String s1 = String.valueOf(v1);String s2 = String.valueOf(v2);String s2 = String.valueOf(v2);String s3 = String.valueOf(v3);String s3 = String.valueOf(v3);

"-12"s1

"3.14"s2

"a"s3

Final variablesFinal variables

ConsiderConsiderfinal String POEM_TITLE = “Appearance of Brown";final String POEM_TITLE = “Appearance of Brown";

final String WARNING = “Weather ball is black";final String WARNING = “Weather ball is black";

What is the representation?What is the representation?

"Appearance of Brown"POEM_TITLE

"Weather ball is black"WARNING

The locks indicate the memory location holds constants

Final variablesFinal variables

objecttype

constantValue

In general, these attributes can bemodified through member methods

The reference cannot bemodified once it is established

RectangleRectangle

The third and fourthparameters of theRectangle constructorspecify the dimensions ofthe new Rectangle

The first two parameters of theRectangle constructor specify theposition of the upper-left-handcorner of the new Rectangle

int x = 3;int y = 4;int width = 5;int height = 2;Rectangle r = new Rectangle(x, y, width, height);

3x

4y

Rectangle:

5width

height 2

r

5

2(3, 4)

ConsiderConsiderfinal Rectangle BLOCK = new Rectangle(6,final Rectangle BLOCK = new Rectangle(6, 9,9, 4,4, 2);2);

BLOCK.setLocation(1,BLOCK.setLocation(1, 4);4);

BLOCK.resize(8,BLOCK.resize(8, 3); 3);

ConsiderConsiderfinal Rectangle BLOCK = new Rectangle(6,final Rectangle BLOCK = new Rectangle(6, 9,9, 4,4, 2);2);

BLOCK.setLocation(1,BLOCK.setLocation(1, 4);4);

BLOCK.resize(8,BLOCK.resize(8, 3); 3);

RectangleRectangle

Rectangle:BLOCK

4

2(6, 9)

Rectangle:BLOCK

8

3(1, 4)

Final variablesFinal variables

ConsiderConsiderfinal String LANGUAGE = "Java";final String LANGUAGE = "Java";

"Java"

The contents are immutable becausethere are no String methods thatallow the contents to be changed

The reference cannot bemodified once it is

established

LANGUAGE

A bit of humor…A bit of humor…