0% found this document useful (0 votes)
14 views107 pages

3 cps209 Classes Objects 2

The document is a lecture outline for CPS 209, focusing on advanced Java concepts such as classes, objects, static members, and built-in Java classes like Scanner and ArrayList. It includes explanations of static variables, methods, and the differences between arrays and strings, as well as the introduction of BigInteger and object factories. The course material is copyrighted and intended solely for registered students of the course.

Uploaded by

qasemali200502
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views107 pages

3 cps209 Classes Objects 2

The document is a lecture outline for CPS 209, focusing on advanced Java concepts such as classes, objects, static members, and built-in Java classes like Scanner and ArrayList. It includes explanations of static variables, methods, and the differences between arrays and strings, as well as the introduction of BigInteger and object factories. The course material is copyrighted and intended solely for registered students of the course.

Uploaded by

qasemali200502
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 107

CPS 209

Computer Science II
Prof. Alex Ufkes

Topic 3: More Classes & Objects in Java


Notice!

Obligatory copyright notice in the age of digital


delivery and online classrooms:

The copyright to this original work is held by Alex Ufkes. Students


registered in course C/CPS 209 can use this material for the purposes
of this course but no other use is permitted, and there can be no sale
or transfer or use of the work for any other purpose without explicit
permission of Alex Ufkes.

© Alex Ufkes, 2020, 2025 2


Course Administration

• Nothing big to announce


• Work on lab problems
• Project #1 description
coming “soon”

© Alex Ufkes, 2020, 2025 3


Any Questions?

© Alex Ufkes, 2020, 2025 4


Let’s Get Started!

© Alex Ufkes, 2020, 2025 5


Previously

© Alex Ufkes, 2020, 2025 6


Previously

Arrays.equals()

© Alex Ufkes, 2020, 2025 7


© Alex Ufkes, 2020, 2025 8
Previously

© Alex Ufkes, 2020, 2025 9


Previously

Now we need a Person object


to create an Account.

© Alex Ufkes, 2020, 2025 10


Today:

Continuing Classes and Objects in Java:


• Static members
• More useful built-in Java classes
o Scanner, BigInteger, ArrayList,
primitive wrappers and their uses
• Static factory methods
• Nested and local classes

© Alex Ufkes, 2020, 2025 11


Static Members

© Alex Ufkes, 2020, 2025 12


Meaning what, exactly?

© Alex Ufkes, 2020, 2025 13


• This is an instance variable of Counter
• Each Counter object has a separate copy

© Alex Ufkes, 2020, 2025 14


Separate Copy?

© Alex Ufkes, 2020, 2025 15


• Static variables are shared
between all instances!
• If one object modifies it,
that change is reflected in
all other instances.

• Each time we create a new Person,


we increment num_people.
• After five Person objects are created,
num_people will equal 5.

© Alex Ufkes, 2020, 2025 16


© Alex Ufkes, 2020, 2025 17
Implications

We need not create an object to access static variables!

© Alex Ufkes, 2020, 2025 18


Remember Math?

Math is a class! We didn’t create an instance of Math.

© Alex Ufkes, 2020, 2025 19


Everything in Math is Static

• cos(), sin(), sqrt() are all


static methods.
• We don’t have to create a
Math object to use them
• Can we create a Math
object…?

© Alex Ufkes, 2020, 2025 20


Math Objects?

• Apparently not. Who can guess why?


• Math’s constructor is private

© Alex Ufkes, 2020, 2025 21


https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Math.html
© Alex Ufkes, 2020, 2025 22
Arrays Class

import java.util.Arrays;

Look familiar?
• Like Math, methods in the
Arrays class are all static.
• String methods belong to
String objects
• Arrays methods belong to
the Arrays class

© Alex Ufkes, 2020, 2025 23


Arrays Class

Same as Math, private constructor.

© Alex Ufkes, 2020, 2025 24


https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html

© Alex Ufkes, 2020, 2025 25


We have non-static methods:
• We say: str.<method>()
• Not: String.<method>(str)

Still have some


static methods

© Alex Ufkes, 2020, 2025 26


Arrays VS Strings

Speaking of arrays and strings, what can we say about this?

For strings, length() is a method. For arrays, length is a value (variable)!


© Alex Ufkes, 2020, 2025 27
str.length() VS arr.length

String length()

What is arr.length? It’s clearly public, some sort of integer would make sense.

It is an int:
• It is declared final, which means it cannot
be mutated once assigned.
• It also means the maximum size for an array
in Java is 2,147,483,647 elements!
• 2,147,483,647 ints @ 4 bytes per int =>8Gb

© Alex Ufkes, 2020, 2025 28


final Variables

Once assigned a value, they cannot be mutated:

© Alex Ufkes, 2020, 2025 29


final Variables

Once assigned a value, they cannot be mutated:

© Alex Ufkes, 2020, 2025 30


Remember System.out.println?

• “System is a class, out is a static instance


of another class, println is a method.”
• “There’s so much in a simple print
statement for us to unpack.”
• This makes a bit more sense now, even if
it doesn’t yet make total sense.
© Alex Ufkes, 2020, 2025 31
For that matter, remember main()?

• We don’t need an instance of


HelloWorld to execute main!
• This is why it must be static. We can’t
create a HelloWorld object until our
program is executing to begin with.

© Alex Ufkes, 2020, 2025 32


• We don’t *need* to know what arr.length is to use it.
• We don’t *need* to know what Math.PI is to use it.
• However, it gives us a sense of confidence to know that Java is
bound by its own rules, and that those rules can be understood.
• Digging into the nuts and bolts of a language isn’t just idle curiosity
• It’s the difference between knowing how to use a tool and
knowing how that tool works.

© Alex Ufkes, 2020, 2025 33


Built-in Java Classes and Methods

Now that we understand the basics of Classes in Java:


Syntax, constructors, instance variables/methods, static variables/methods,
access specifiers, constructor/method overloading, and so on.

We can now explore several more useful built-in Classes


• Scanner for user input, BigInteger for handling big integers
• ArrayLists and primitive wrappers to make up for the shortcomings of
regular arrays and get us closer to Python-style lists
• And more!

© Alex Ufkes, 2020, 2025 34


© Alex Ufkes, 2020, 2025 35
User Input with Scanner

Quick intro to Scanner:

Requires an import

© Alex Ufkes, 2020, 2025 36


Constructor argument:
• Tells the Scanner where
to read input from.
Data type: Identifier: • System.in refers to the
Scanner class Can be anything legal keyboard, by default.
• Can also be a String, file,
input stream, etc.

© Alex Ufkes, 2020, 2025 37


Grab the next integer
from System.in

Declare an
integer Using the Scanner we declared….

© Alex Ufkes, 2020, 2025 38


© Alex Ufkes, 2020, 2025 39
Huh?

• nextLine() read “\n” from


the buffer after 87.9 was
entered.
• next() read the string Hello.

© Alex Ufkes, 2020, 2025 40


Huh?

© Alex Ufkes, 2020, 2025 41


Scanning Strings

Works the same, but we’re reading from a string instead of the keyboard:

• Of course, we must know which type we’re reading.


• Alternatively, we can validate using hasNextInt(), and so on.
© Alex Ufkes, 2020, 2025 42
System.in is an
InputStream

© Alex Ufkes, 2020, 2025 43


https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Scanner.html

© Alex Ufkes, 2020, 2025 44


Array wrapper with added functionality!

Operations on ArrayLists more closely


resemble Python Lists.

© Alex Ufkes, 2020, 2025 45


ArrayList Class

ArrayList<Type> variableName

Type of an ArrayList must be an object

© Alex Ufkes, 2020, 2025 46


ArrayList
is a class:

Just like Scanner,


String, etc.
Values/properties

Methods

© Alex Ufkes, 2020, 2025 47


Create and Add Elements

Follows typical object


declaration syntax.

• Add as many elements as we want.


• Items appended to end of list,
ArrayList grows as needed.
• Very powerful, the programmer is
© Alex Ufkes, 2020, 2025 not responsible for basic behavior. 48
Retrieve Elements

Use add() method,


provide a String argument

• To retrieve an individual element,


use the get() method.
• Argument to get() is an index.
• Remember: zero-indexed!

© Alex Ufkes, 2020, 2025 49


Print all Elements

Use size() method to


get number of elements

get(i) grabs one element at a time in the loop

© Alex Ufkes, 2020, 2025 50


Modify Elements

• Use the set() method.


• Takes two arguments:
index and new value.

© Alex Ufkes, 2020, 2025 51


Insert Elements

We’ve seen how to use add() to insert items at the end of the list.

add() can also be used to insert items in the middle of the list.
© Alex Ufkes, 2020, 2025 52
Insert Elements

If we provide add with 2 arguments, an index


and a value, we insert an item at that index.

© Alex Ufkes, 2020, 2025 53


Remove Elements

remove() method accepts one


argument, the index to be removed.

© Alex Ufkes, 2020, 2025 54


Why ArrayLists?

Everything we can do with an ArrayList can be


done with a standard array.

The difference is that ArrayList provides methods to achieve all


these operations for us. Already built in.

With standard arrays, we must code all the functionality


ourselves for inserting and removing elements.

© Alex Ufkes, 2020, 2025 55


ArrayList Limitations

Recall: Type of an ArrayList must be a Class.


ArrayLists hold objects.
The examples we’ve seen so far have been using an
ArrayList of Strings, which are objects.
What if we want an array list of integers? Floats?
Booleans? These are not objects.

© Alex Ufkes, 2020, 2025 56


What about primitive types?

• It turns out that for every primitive type,


Java provides an equivalent object type.
• The primitive value is boxed in an object.
• These objects are known as wrappers
• Each primitive type has an object wrapper

© Alex Ufkes, 2020, 2025 57


© Alex Ufkes, 2020, 2025 58
Boxing & Unboxing

• Double d1 can be declared using


standard primitive declaration syntax
• This is a shortcut afforded to us by Java.
• Called auto-boxing
• We can also declare a Double using the
standard object declaration syntax.
• Literal or variable passed to constructor
© Alex Ufkes, 2020, 2025 59
Boxing & Unboxing

Auto-boxing

Auto-unbox to perform addition

© Alex Ufkes, 2020, 2025 60


Boxing & Unboxing

Auto-boxing

Auto-unbox to perform addition

Auto-box result of addition to


store back in object d1.
• Wrapper objects can be used like their wrapped primitives
• They also provide advantages due to being objects, such
as being members of ArrayLists
© Alex Ufkes, 2020, 2025 61
for-each Loop + ArrayList

Works the same way:


• Type of e can now be
Integer or int
• Autoboxing/unboxing
works here also

© Alex Ufkes, 2020, 2025 62


https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/ArrayList.html

© Alex Ufkes, 2020, 2025 63


Integer
© Alex Ufkes, 2020, 2025 64
BigInteger

Grows arbitrarily large like a Python integer:

• We must provide a String


to the constructor.
• Who can guess why?
• Integer literals in Java are
still bound by their type!
• BigIntegers are internally
represented as Strings
• BigInteger arithmetic is
done via method calls.

(import java.math.*; to use)


© Alex Ufkes, 2020, 2025 65
BigInteger

Grows arbitrarily large like a Python integer:

(import java.math.*; to use)


© Alex Ufkes, 2020, 2025 66
BigInteger

Convert back to integer?

This result can be


represented by an int.

© Alex Ufkes, 2020, 2025 67


BigInteger

Convert back to integer?

• Use Scanner to read


from a string!
• nextInt() works
just the same.

© Alex Ufkes, 2020, 2025 68


BigInteger

How about this?

© Alex Ufkes, 2020, 2025 69


BigInteger

How about this?

What we have here is a failure to parse.

© Alex Ufkes, 2020, 2025 70


BigInteger

Same idea:

© Alex Ufkes, 2020, 2025 71


Object Factories

© Alex Ufkes, 2020, 2025 72


Object Factories

• If a class has a private constructor, no objects


of that class can be created outside that class.
• However, we can still create and return objects
from within that class.
• How? By using a static factory method.

© Alex Ufkes, 2020, 2025 73


Static Factory Method

• Constructor is private!
• It can still be invoked by factory
method create()
• For this to work, create() must
be static. Why?
• If it’s not, we need to create an
object to invoke it.
• If constructor is private, we can’t
create a Card object.

© Alex Ufkes, 2020, 2025 74


Invoke static factory method
Card.create() to instantiate
a Card object.

Invoking Card constructor


using new keyword fails.

© Alex Ufkes, 2020, 2025 75


Static Factory Method

• This is very useful! We can control very precisely the


conditions for creating a new object.
• Input arguments don’t make sense? Return null.
• You’ve created too many objects? Return null.
• You already created an object with those parameters?
Return a reference to that previous object.
• Consider Card. If we’re dealing with one deck, we may
not want to allow duplicates to be instantiated.
• Let’s try it out!

© Alex Ufkes, 2020, 2025 76


• Test if rank is between 2 and 14. If not,
return null without creating the card.
• Test if suit is one of the four valid suits.
o Note this neat trick for doing so.
o indexOf() returns -1 if not found.
• If rank and suit are valid, create and
return a new Card object.

© Alex Ufkes, 2020, 2025 77


Let’s also create a simple
toString() method to
test it out.

© Alex Ufkes, 2020, 2025 78


Limit the number of Card objects:

• Static variable belongs to the class.


• Return null once we’ve created 5 cards
• Every time we create a new Card,
increment nCards.

© Alex Ufkes, 2020, 2025 79


Limit the number of Card objects:

© Alex Ufkes, 2020, 2025 80


© Alex Ufkes, 2020, 2025 81
Nested & Local Classes

© Alex Ufkes, 2020, 2025 82


A Class Within a Class

Just like nested loops

Consider: Class B is defined inside Class A (B is nested in A)


• B objects can be created inside the instance methods of A
• B objects cannot exist on their own without Class A
• We can’t have a B object without first having an A object
• This is different from inheritance! (Next class)

© Alex Ufkes, 2020, 2025 83


• We have a full class definition encapsulated
in another class definition.
• PointList is the outer class, Point is the inner.
• Point doesn’t exist outside of PointList.

© Alex Ufkes, 2020, 2025 84


© Alex Ufkes, 2020, 2025 85
Consider: Class B is defined inside Class A (B is nested in A)
• B objects can only be created inside the instance methods of A
• B objects cannot exist on their own without Class A
• We can’t have a B object without first having an A object
• Unless the nested class is declared as public.

This works because Point


is declared as public
© Alex Ufkes, 2020, 2025 86
© Alex Ufkes, 2020, 2025 87
Static variable to count the number of points created.

• In Point constructor, increment nPts.


• Notice, Point is accessing a class
(static) variable of PointList.

Nested Classes:
Accessing Fields?
© Alex Ufkes, 2020, 2025 88
© Alex Ufkes, 2020, 2025 89
Private? Point can access
private members of PointList

© Alex Ufkes, 2020, 2025 90


Nested Classes: Shadowing

• We’ve seen that local variables (in a method) can shadow class
instance variables.

• Use this to specify


instance variables
• Without this, we
refer to local variables.

© Alex Ufkes, 2020, 2025 91


Nested Classes: Shadowing

What happens if an inner class member shadows an outer class member?

Can we access x and y in


PointList from Point?

this.x, this.y refer


to x and y in Point

© Alex Ufkes, 2020, 2025 92


Nested Classes: Shadowing

• If we’re inside Point, this refers to


the Point object we’re currently in.
• Recall: We can’t have a Point object
without a PointList object.
• To access the PointList object that
the current Point object is in, we
use PointList.this

© Alex Ufkes, 2020, 2025 93


The Rabbit Hole Goes Ever Deeper

© Alex Ufkes, 2020, 2025 94


Local class Point

© Alex Ufkes, 2020, 2025 95


• Local classes are only visible inside
the method in which they’re defined.
• In this case, the main() method.
• Notice, we need not specify the class
as public.
• Its scope is already limited to the
method it’s defined in.

© Alex Ufkes, 2020, 2025 96


• Scope rules for local classes are
similar to nested classes.
• A local class can access all the
methods and instance variables
of its encompassing class.

© Alex Ufkes, 2020, 2025 97


© Alex Ufkes, 2020, 2025 98
Use the same syntax as
with nested classes.

© Alex Ufkes, 2020, 2025 99


Local Classes: Local Variables

• Nested classes can access


local variables of its
encompassing method….
• But only under specific
conditions.
• The variable must be final,
or effectively final.

© Alex Ufkes, 2020, 2025 100


Local Classes: Local Variables

Effectively final
• The variable is not explicitly
declared final, but never
actually changes.
• We can access it in our nested
class, but we can’t modify it.

© Alex Ufkes, 2020, 2025 101


Local Classes: Local Variables

Effectively final
• The variable is not explicitly
declared final, but never
actually changes.
• We can access it in our nested
class, but we can’t modify it.
• The encompassing method
cannot modify it either.
• Test: Could the variable be
declared final without compile
errors?
• If so, it is effectively final
© Alex Ufkes, 2020, 2025 102
Zero-One-Infinity

A rule of thumb that states:


• Arbitrary limits on the the number of instances of a particular entity
should not be allowed.
• Something is forbidden, allowed once, or allowed any number of times.
• A class may have one superclass, but any number of subclasses.
• It would make no sense to limit subclasses to seven, for example.
• Loops can have any number of nested layers, arrays can have any
arbitrary number of dimensions, etc.

© Alex Ufkes, 2020, 2025 103


Zero-One-Infinity

• Nested classes adhere to this principle as well.


• We can nest classes within classes within classes.
• All the rules we’ve seen remain the same, just
extrapolated to multiple layers.
In practice, in general:
• Arrays > 3 dimensions? Rethink your code.
• Loops > 3 layers? Rethink your code.
• Nested classes > 2 layers? Rethink your code.

© Alex Ufkes, 2020, 2025 104


Summary:

Continuing Classes and Objects in Java:


• Static members, explaining main()
• Useful built-in Java classes
o Scanner, BigInteger, ArrayList,
primitive wrappers and their uses
• Static factory methods
• Nested and local classes

© Alex Ufkes, 2020, 2025 105


Next Class:

Inheritance
&
Polymorphism

© Alex Ufkes, 2020, 2025 106


© Alex Ufkes, 2020, 2025 107

You might also like