0% found this document useful (0 votes)
3 views

2_cps209_classes_objects_1

The document is a lecture outline for CPS 209, focusing on classes and objects in Java, including topics like arrays, object equality, and creating custom classes. It emphasizes the differences between Java and Python, particularly in terms of data structures and object behavior. Additionally, it covers the importance of access specifiers, mutators, and constructors in class design.

Uploaded by

qasemali200502
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

2_cps209_classes_objects_1

The document is a lecture outline for CPS 209, focusing on classes and objects in Java, including topics like arrays, object equality, and creating custom classes. It emphasizes the differences between Java and Python, particularly in terms of data structures and object behavior. Additionally, it covers the importance of access specifiers, mutators, and constructors in class design.

Uploaded by

qasemali200502
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

CPS 209

Computer Science II
Prof. Alex Ufkes

Topic 2: 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

Lab #1 homework is posted


• Submit on D2L by January 26, 11:59pm

© Alex Ufkes, 2020, 2025 3


Let’s Get Started!

© Alex Ufkes, 2020, 2025 4


Previously

© Alex Ufkes, 2020, 2025 5


Previously

• Nesting control structures in Java works the same way as Python


• In Java, however, curly braces indicate scope (not whitespace)
public static void main(String args[])
{
int a = 7;
if (a > 0) {
System.out.println("Positive");
}
else {
if (a > 0) {
System.out.println("Negative");
}
else {
System.out.println("Zero");
}
}
© Alex Ufkes, 2020, 2025 } 6
Previously

public static int rollSnakeEyes ()


{ public static int rollSnakeEyes ()
Random rand = new Random(); {
int a = rand.nextInt(5) + 1; Random rand = new Random();
int b = rand.nextInt(5) + 1; int a, b, count = 0;
int count = 1; do {
while (a + b != 2) { a = rand.nextInt(5) + 1;
a = rand.nextInt(5) + 1; b = rand.nextInt(5) + 1;
b = rand.nextInt(5) + 1; count += 1;
count += 1; } while (a + b != 2);
} return count;
return count; }
}

© Alex Ufkes, 2020, 2025 7


Previously

public static void main(String args[])


{
System.out.println("String methods:");
String s = "Hello, world!";
Calling an object’s methods in Java
System.out.println(s.toLowerCase());
is very similar to Python, both
System.out.println(s.toUpperCase());
syntactically and semantically.
System.out.println(s.substring(5));
System.out.println(s.substring(3, 8));
String s2 = s.replaceAll("ello", "owdy");
System.out.println(s2);
}

© Alex Ufkes, 2020, 2025 8


Today:

Classes and Objects in Java:


• Arrays in Java, Useful array methods
• Sequence equality: object VS content
• Creating and using our own classes
• Class and object fundamentals:
o Instance variables, access control, and more

© Alex Ufkes, 2020, 2025 9


Java {Arrays}
VS
Python [Lists]

© Alex Ufkes, 2020, 2025 10


Arrays in Java

Lists in Python are heterogeneous: They can hold any type, any object
Arrays in Java are homogeneous: Can only hold items of a single type

int[] list = new int[5];

[] indicates Array Size of the


array. identifier array

© Alex Ufkes, 2020, 2025 11


Arrays in Java: Initialization

int[] list = new int[5];


list

By default, array values in Java


are initialized to zero

© Alex Ufkes, 2020, 2025 12


Arrays in Java: Initialization

Initialize with literals:

int[] list = {-33, 4, 37, 2};

Content equality? Not the same as Python…

© Alex Ufkes, 2020, 2025 13


Arrays in Java: Access Elements

We have indexing, but alas, no slicing:

© Alex Ufkes, 2020, 2025 14


Arrays in Java: N-dimensions?

Convention is as follows, nest as deeply as you need to:

© Alex Ufkes, 2020, 2025 15


2D Arrays are Fake!

They’re just arrays of arrays: A 2D array is an array of 1D arrays.

© Alex Ufkes, 2020, 2025 16


Arrays in Java: For-each

Just like Python for loops operate over any iterable,


Java has a special for loop style that behaves similarly:

• e will take the value of each


element in the array nums.
• Written this way, the loop will
automatically go through each
element in nums.
• Don’t need to keep track of index
or conditions, it’s done for us.

© Alex Ufkes, 2020, 2025 17


Arrays in Java: For-each

Just like Python for loops operate over any iterable,


Java has a special for loop style that behaves similarly:

© Alex Ufkes, 2020, 2025 18


• Printing objects in Java very often does
not yield anything human-readable.
• Use Arrays.toString() instead

© Alex Ufkes, 2020, 2025 19


Arrays in Java: Handy Methods

A String is backed by an array of characters, but a String


is not the same thing as an array of characters!

© Alex Ufkes, 2020, 2025 20


Arrays in Java: Handy Methods

Conversion back and forth is possible, just not as slick as Python:

© Alex Ufkes, 2020, 2025 21


Arrays in Java: Handy Methods

• Sorting modifies original array!


• Same is true of lists in Python.
• Java arrays, like Python lists, are
mutable.

© Alex Ufkes, 2020, 2025 22


Arrays in Java: Mutable?

Behavior is like Python Lists:

© Alex Ufkes, 2020, 2025 23


Arrays in Java: Handy Methods

double[] list1 = {1, 2, 3, 4};


double[] list2 = list1;

© Alex Ufkes, 2020, 2025 24


Arrays in Java: Handy Methods

clone() gets us a new array object:

© Alex Ufkes, 2020, 2025 25


Array Equality?

• When we use == with objects, we test object equality.


• “Are these two variables referring to the same object?”
• Declaring arrays with identical literals yields different objects:

© Alex Ufkes, 2020, 2025 26


Array Content Equality

Use Arrays.equals()

© Alex Ufkes, 2020, 2025 27


Sequence Equality:
Python != Java

© Alex Ufkes, 2020, 2025 28


Sequence Equality

In Python, the == operator checks content equality for all sequences.


To check object equality, we would say id(s1)==id(s2) or s1 is s2

© Alex Ufkes, 2020, 2025 29


Strings in Java: Equality

String word = “Hello, World!”;

Could also be written:

String word = new String(“Hello, World!”);

Though they are not exactly the same…

© Alex Ufkes, 2020, 2025 30


Strings in Java: Equality

When we declare a String object, it gets created in memory:

String word1 = “Hello”;

“Hello”

© Alex Ufkes, 2020, 2025 31


Strings in Java: Equality

What happens when two strings are the same?

String word1 = “Hello”; String word2 = “Hello”;

When strings are … and have the


declared in this manner: same value

“Hello” They will refer to


This is also
true in Python! the same object!

© Alex Ufkes, 2020, 2025 32


This is also true in Python!

© Alex Ufkes, 2020, 2025 33


Strings in Java: Equality

What happens when two strings are the same?

String word1 = “Hello”; String word2 = “Hello”;


word2 = “World”;

• If we change the value,


a new object is created “Hello” “World”
• In Java, as in Python,
strings are immutable
© Alex Ufkes, 2020, 2025 34
Strings in Java: Equality

This only applies to this style of declaration:

String word1 = “Hello”;


If we declare our strings in the traditional object style using new:

String w1 = new String (“Hello”); String w2 = new String (“Hello”);

We get different
“Hello” objects! “Hello”
© Alex Ufkes, 2020, 2025 35
Why Does This Matter?

It matters when we want to check if two strings are “equal”

This is what we might expect, except….


© Alex Ufkes, 2020, 2025 36
Why Does This Matter?

It matters when we want to check if two strings are “equal”

?
© Alex Ufkes, 2020, 2025 37
Strings in Java: Equality

Using == checks if two strings are the same OBJECT


It does NOT check if they have the same value.
Here, checking word1==word2 will be false

String w1 = new String (“Hello”); String w2 = new String (“Hello”);

“Hello” “Hello”
© Alex Ufkes, 2020, 2025 38
Strings in Java: Equality

So how do we check if strings have the same value?

string1.equals(string2)

© Alex Ufkes, 2020, 2025 39


string1.equals(string2)

© Alex Ufkes, 2020, 2025 40


string1.equalsIgnoreCase(string2)

© Alex Ufkes, 2020, 2025 41


Quick Sequence Summary:

In Python: In Java:
• Strings are immutable • Strings are immutable
• == tests content equality • == tests object equality
• Lists are heterogeneous (when comparing objects)
• Lists are mutable • Arrays are homogeneous
• Lists can grow or shrink • Arrays are mutable
(append(), remove()) • Arrays are fixed in size

Next week we’ll see Java’s ArrayList class, which more closely
mirrors the utility and capability of Python Lists

© Alex Ufkes, 2020, 2025 42


Creating our own classes
© Alex Ufkes, 2020, 2025 43
A Class is a blueprint for creating objects

If the class is the blueprint…


© Alex Ufkes, 2020, 2025 44
…the actual car is the object.
© Alex Ufkes, 2020, 2025 45
Objects VS Primitives

Literals are instances of primitives:


• 7 is an instance of an int
• 3.14 is an instance of a double
• Both int and double are primitive types. They
have value, but no associated behavior.

Objects are instances of Classes:


• A string object is an instance of the String class
in the same way that 7 is an instance of int
• Classes may implement methods (behaviors)
that their objects can invoke.
• I.e. subString(), charAt(), etc. from String class

© Alex Ufkes, 2020, 2025 46


Consider a simple click counter:

© Alex Ufkes, 2020, 2025 47


Consider a simple click counter:
What properties is this represented by? What behaviors?

Properties

Behaviors

© Alex Ufkes, 2020, 2025 48


Blueprint:

© Alex Ufkes, 2020, 2025 49


Blueprint:

© Alex Ufkes, 2020, 2025 50


Blueprint:

Different instances can have


different property values

© Alex Ufkes, 2020, 2025 51


Even though Counter is completely empty, we can still
create an instance of Counter in our main method:

© Alex Ufkes, 2020, 2025 52


Let’s add some properties and behaviors to Counter

• This is an instance variable of Counter


• Each Counter object has a separate copy

Access specifier:
• Private means this variable cannot be
accessed from outside the Counter class.

© Alex Ufkes, 2020, 2025 53


Access specifier:
• Private means this variable cannot be
accessed from outside the Counter class.

© Alex Ufkes, 2020, 2025 54


This is a
method

Access specifier:
Public means this method can be
accessed from outside the Counter class.

© Alex Ufkes, 2020, 2025 55


More methods!
• Notice in particular get_value()
• value is private, so we can’t access it directly.
• Instead, we create a get_value() method
• This method is public, so it can be called from
outside of counter.

© Alex Ufkes, 2020, 2025 56


© Alex Ufkes, 2020, 2025 57
Modifies object data

© Alex Ufkes, 2020, 2025 58


Returns object data

© Alex Ufkes, 2020, 2025 59


sets and gets!

© Alex Ufkes, 2020, 2025 60


Mutators

Accessor

© Alex Ufkes, 2020, 2025 61


But Why?

Why bother with sets and gets when we can just make the instance variable public?

?
© Alex Ufkes, 2020, 2025 62
But Why?

Why bother with sets and gets when we can just make the instance variable public?

• Classes model specific concepts within a real-world problem domain.


• Set methods ensure all possible operations upon the data fields of a
given class fall within the intended domain of that class.
For example:
• Our Clicker class has two mutator methods: click() and reset().
• They add 1 and set to 0, respectively. No other operations possible!
• Were value public, the programmer would be free to add 17 to it.
• This is not possible given the actual physical system we are trying to
represent with our Clicker class.

© Alex Ufkes, 2020, 2025 63


But Why?

For example:
• Were value public, the programmer would be free to add 17 to it.
• This is not possible given the actual physical system we are trying to
represent with our Clicker class.

© Alex Ufkes, 2020, 2025 64


• Value not initialized!
• We’re in luck, Java initializes
instance variables to 0
• Still bad practice though
• Better to use a constructor

© Alex Ufkes, 2020, 2025 65


Constructors

A constructor can be used to initialize


object values or perform some behavior
upon object creation.

Every class must have a constructor. We


haven’t created one yet, but Java
synthesizes a default, empty constructor
for you if you don’t provide your own.

© Alex Ufkes, 2020, 2025 66


Constructors

• A constructor looks like a method.


• The name of a constructor must
match the name of the class

© Alex Ufkes, 2020, 2025 67


Constructors

Constructors are invoked when we create a new object:

• When we use new to create an object, we invoke its constructor.


• In this case, the constructor initializes value to zero.
• What if we want to initialize value to some other amount?
© Alex Ufkes, 2020, 2025 68
Constructor Overloading

Java can differentiate between constructors


so long as their parameter list is different.

© Alex Ufkes, 2020, 2025 69


Constructor Overloading

© Alex Ufkes, 2020, 2025 70


© Alex Ufkes, 2020, 2025 71
Method Overloading?

Two methods can have the same name IF


their parameter lists are different:

• Java knows which method to use


based on the arguments provided.
• This is how add() works.
• Two arguments returns their sum
• One argument adds to itself.

© Alex Ufkes, 2020, 2025 72


© Alex Ufkes, 2020, 2025 73
Access Specifiers
Access specifiers determine whether other classes
or objects can invoke a particular method or
access a particular field.

© Alex Ufkes, 2020, 2025 74


Access Specifiers

Access specifiers determine whether other classes or objects can


invoke a particular method or access a particular field.

public:
Member (variable or method)
is visible to all classes.

© Alex Ufkes, 2020, 2025 75


public: visible to all classes.

In Counter class, click(), reset(), getValue() methods are public.


Thus, we can call them from another class, CounterTester.
© Alex Ufkes, 2020, 2025 76
More Generally:

Objects can always access their


own variables and methods.

© Alex Ufkes, 2020, 2025 77


Methods can access public members in other classes:

© Alex Ufkes, 2020, 2025 78


private: Accessible by objects of the same class

© Alex Ufkes, 2020, 2025 79


© Alex Ufkes, 2020, 2025 80
© Alex Ufkes, 2020, 2025
invisible! 81
Visible!

© Alex Ufkes, 2020, 2025 82


Instances of the same class can access each other’s private methods/variables!

Visible!

© Alex Ufkes, 2020, 2025 83


String Length?

length() is a public method of class String!

© Alex Ufkes, 2020, 2025 84


Another Class Example!

© Alex Ufkes, 2020, 2025 85


© Alex Ufkes, 2020, 2025 86
© Alex Ufkes, 2020, 2025 87
Another!

© Alex Ufkes, 2020, 2025 88


Notice:
• Only one constructor
• When creating a Person, we MUST
specify name and age!
• The default constructor is not
created once we define our own

© Alex Ufkes, 2020, 2025 89


Notice:
• Only one constructor
• When creating a Person, we
MUST specify name and age!

© Alex Ufkes, 2020, 2025 90


© Alex Ufkes, 2020, 2025 91
Person and Account

We can’t create an Account without providing


a Person as an argument to the constructor.

© Alex Ufkes, 2020, 2025 92


© Alex Ufkes, 2020, 2025 93
© Alex Ufkes, 2020, 2025 94
Problem?

• Parameter names shadow


instance variable names
• Not a compile error!
• Constructor pointlessly assigns
parameters to themselves.

© Alex Ufkes, 2020, 2025 95


“Tim” is not being assigned to the
instance variable. What happens if
we try to print it?

© Alex Ufkes, 2020, 2025 96


this

• this is a reference to the object whose method we are executing.


• When using this we are inside the class, can access private members.
© Alex Ufkes, 2020, 2025 97
Summary:

Classes and Objects in Java:


• Arrays in Java, Useful array methods
• Sequence equality: object VS content
• Creating and using our own classes
• Class and object fundamentals:
o Instance variables, access control,
and more

© Alex Ufkes, 2020, 2025 98


Next Week:

• Static members
• More useful built-in
Java classes
• More class examples

© Alex Ufkes, 2020, 2025 99


© Alex Ufkes, 2020, 2025 100

You might also like