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

M4 OO Programming Objects

Uploaded by

Justin Reynolds
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)
19 views

M4 OO Programming Objects

Uploaded by

Justin Reynolds
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/ 62

OO Programming &

Objects
Programming 1

-1-
Contents
1. Introduction
• Objects, messages, classes
2. Working with objects
• Creating, using and deleting objects
3. Simple objects
• Classes String and StringBuilder
4. Formatting
• Methods printf and format

-2-
Introduction to
objects
Objects 1.5

Object = foundation of
Object-Oriented Programming (OOP)

•An object in our daily lives


– … has properties that make up an object’s state
– … displays a certain behavior
•An object in software
– properties → attributes / fields / class properties
– behavior → methods
•Correlates with an entity
– During database design and generic analysis and
design

-4-
Objects
•Example: An individual ship
– Properties (attributes)
▪ Type: passenger ship, oil tanker, …
▪ Capacity: max cargo tons or max amount of
passengers
▪ Amount of crew currently on board
▪ Length, width, draft
– Behavior
▪ dock, blast horn, lower anchor, turn, …
▪ board passengers, load cargo
•Other examples?

-5-
Which data type to use for ...

•Age? → int

•Percentage? → double

•Name? → String

•Ship?
•Product?
•Person?
•Car?
?
•Trip? Island? Captain?

-6-
Classes & Objects
•A class is a blueprint that describes the properties
and the methods of all objects of a certain type
•An object is a unique instance of a class

-7-
Objects
•Come up with some example of classes and
possible objects of those classes

•Class President
•Objects of class President
barackObama abrahamLincoln

-8-
Objects

-9-
Quiz
•Which of the following are classes and which are
objects?
If it's a class, give examples of possible objects.
If it's an object, what would be a good class name?

● car with license plate "1 ABC 001"


● course
● Lewis Hamilton
● word
● Nationalestraat nr. 5
● bonobo

• Try to come up with some more examples

- 10 -
Classes & Objects
•A class determines the type of an object
•A class defines the properties and methods
•An object is an instance of a class
Class definition Object (instance of a class)

class Car Car herbie = new Car();


Properties (attributes):
color herbie.start();
speed herbie.accelerate(10);
direction herbie.turn(90);
Methods: herbie.break();
start()
break()
accelerate (int speed)
turn(angle)

- 11 -
Method call (message)

Interaction with a car:


Following statement changes the direction of a car:
direction = herbie.turn(angle);

object
method
variable stores
parameter(s)
res t

Interaction with a keyboard:


number = keyboard.nextInt();

- 12 -
Working with
objects
Creating objects 3.2.2

How do you create an object?


● A class is needed
○ Write one (see next week)

Or
○ Use one. Some classes in the Java libraries:
■ Scanner
■ String
■ Random
■ StringBuilder
■ …

● Creating an object
○ Scanner keyboard = new Scanner(System.in);
○ Random rand = new Random(10);
○ StringBuilder builder = new StringBuilder();
- 14 -
Creating objects
How do you create an object?

• new operator + class name + ()


○ allocates memory to store the object
○ returns a reference to the object that was created

Random rand = new Random(10);


StringBuilder builder = new StringBuilder();

How do you initialise an object?


• through optional parameters listed in between the
parentheses that follow the name of the class
Parentheses (AK ro n
– Random rand = new Random(10);
brackets) are ma at
– StringBuilder builder = new StringBuilder();
even if no parameters are
present

- 15 -
Creating objects

How is an object initialised?

• new operator + class name + (): calls a constructor (which


is a special kind of method)
• Constructors always have the same name as their class
• Each constructor call results in a new object

• Some examples:
Scanner keyboard = new Scanner(System.in); A single parameter
Random getal = new Random();
Rectangle box = new Rectangle(10,6); No parameters

2 parameters
Capi letter!

- 16 -
Random
Generating random numbers
Using classes & objects: Random 6,9

In §6.9 Sec re andom is used instea of Ran om,


How can we generate but a l information in §6.9 is still relevant!
a random number?
Use the class Random.

There are two constructors:


•Random()→ generates different numbers for each instance

•Random(long seed)→ generates the same sequence of


numbers for each specific seed given

Creating multiple instances of Random


with the same seed will generate the same
number series In act, Random generates a seq ence of
pse o-ran om n mbers base on a mathematical
form la
- 18 -
Using classes & objects: Random

Some useful methods

• nextInt(int n) generates a random whole number


between 0 (inclusive) and n (exclusive) 0 <= result < n

• nextDouble() generates a random number between 0


(inclusive) and 1 (exclusive) 0 <= result < 1

• nextBoolean() generates a random boolean value


true or false

- 19 -
Using classes & objects: Random

How can we use an object?

• It’s only possible to access public properties and methods

• To use an object, write its name followed by a dot followed


by the name of the public method or property that you’d like
to call or access
Note: Random is the name of the class
and random is the name of the object
Random random = new Random();
int number = random.nextInt(); objectname.methodname()

- 20 -
Using objects: some questions

Given this declaration and initialisation ...


Random generator = new Random();

… how would you simulate rolling a single die?

int die = generator.nextInt(6) + 1;

… how would you simulate a coin toss?


(at least 2 possibilities)
boolean coinA = generator.nextBoolean();
int coinB = generator.nextInt(2);

- 21 -
Using objects: some questions

Given this declaration and initialisation ...


Random generator = new Random();

… which range of numbers is generated from


the following piece of code?
int number = generator.nextInt(50) + 50;

… how can you generate a three-digit number?


int number = generator.nextInt(900) + 100;

Ex04.01: Lottery
- 22 -
Exercises
•Ex04.01: Lottery

- 23 -
Referencing
an object
Reference

What is the result of declaration and initialisation?


• A reference to the newly created object is assigned to the variable:
type name = initialValue

Random generator = new Random();

• Putting initialisation on a separate line (same effect):

Random generator; dec aration


Creation of the object
generator = new Random(); Assignment (of the re erence)
Stack memory Heap memory

generator Random
object

The variable has a reference to…


… the object that was create
- 25 -
Reference

Can there be more than one reference to an object?


Random randomOne;
Random randomTwo;
randomOne = new Random(42);
randomTwo = randomOne;

Stack Heap
Wo ld it be possib e for a
randomOne re erence to not refer to
Random any object at al ?
object
randomTwo

- 26 -
Heads up!
Will not compile.
java: variable generator might not have been
initialized

Random generator;
int random = generator.nextInt();

generator

Random generator = new Random();


OK
int random = generator.nextInt();

Random
generator
object

- 27 -
Reference
int i;
Assignment (of primitive types): content of i is copied to j
int j;
→ i and j have the same content: 7
i = 7;
j = i; // j is now also 7
i++; // i is 8, j is still 7
System.out.println(j); // 7

Player player1;
Player player2;
player1 = new Player("hunter25", 3); // 3 lives
player2 = player1; // player2 also refers to "hunter25"
player1.extraLife();
System.out.println(player2.getLives()); // 4!
Assignment (of reference types): content of player1 (reference to the object) is copied to player2
→ player1 and player2 now refer to the same object

As a consequence, any change on the object via player1 can be observed via player2 and vice versa
- 28 -
package and
import
What is a package? 2.5.1 & 3.2.5

• Each class belongs to a package


– class Random belongs to package java.util
– the fully qualified name of this class is
java.util.Random

• If
we want to refer to a class by its name only,
an import statement is needed
Replacing Random with *
import java.util.Random; imports all classes from java.util

Random generator = new Random();

- 30 -
Package and import

How does the compiler find the correct class?

•Using import:
import java.util.Random;
// …
When sing import, just
Random generator = new Random();
the name o the c ass ill
suffice

•Without using import:


java.util.Random generator = new java.util.Random();

Witho t import yo ’ll have


to se the ly alified name

- 31 -
Package and import

How does the compiler find the correct class?

1. Any explicitly imported classes (package + class’ name)


2. Classes that are in your current package
3. Classes from imported packages (import using “*”)

• Some classes are imported automatically:


– the default package (= classes without a package)
– the current package (= classes in the same package)
– package java.lang (= contains Java’s base classes)

- 32 -
Package naming convention

● reverse.domain.of.company.project.internal
○ guarantees world wide uniqueness
○ all lower case
● example
be.kdg.programming1.m4.myutilities

- 33 -
Garbage Collection
Freeing memory / opposite of new
Garbage collection 8,10

How can memory that was allocated for objects


ever be returned to the system again?

• Garbage collection takes care of freeing memory to which


no variable is referring anymore
– A reference disappears ...
▪ … when the reference variable no longer exists (out of scope)
▪ … when value null is assigned to a reference variable

• Garbage collection happens automatically, but never


immediately (on a separate thread with a low priority)

Random
generator
object

- 35 -
Exercises
•Ex04.02: Random

- 36 -
Strings
String 14.1

•The String type is actually a class and as a result


each String in your program is an object
– String is in package java.lang
So, no import is needed!
•Once created, a String object can never be updated.
Each change will lead to the creation of a new String
object.
A String object is immutable!

- 38 -
Creating a String 14.3.1

String theString = "Hello World";


Each String literal
System.out.println(theString); (te t bet een " quotes")
Both represent is an object; no nee to
the same object! write new

System.out.println("Hello World");

String otherString = new String("Hello World");

In this e ample e’re creating a


String object e plicitly… this is
bad practice!

- 39 -
Reading a String

Scanner keyboard = new Scanner(System.in);


wordString wil contain
each character from the inp t
String wordString = keyboard.next(); buffer p to a space or a newline

String sentenceString = keyboard.nextLine();

sentenceString wil contain each


character from the input b ffer up to a
new ine

- 40 -
String methods 14.3

String

Some common methods:


length():Returns the length of the String (= the amount of characters)
charAt(int index): Returns the character at position index (first
character is at position 0)
equals(String string): Compares two Strings, returns true or
false
equalsIgnoreCase(String string): Compares without taking
casing into account
compareTo(String other): Compares two Strings alphabetically,
returns a negative value when this string comes before (<) other , zero when
both strings are equal (=) and a positive value when this string comes after
(>) other
isEmpty(): Checks if a String has a length of zero, returns true or false
Other popular methods: substring, strip, toUpperCase,
toLowerCase, …

- 41 -
String methods examples
Never compare strings using the ==
String male = "John";
operator! (see later)
String female = "Mary";

int amount = male.length(); 4


char ch = female.charAt(3); y
boolean notEqual = male.equals(female); false
boolean equal = male.equals("John"); true
boolean alsoEqual = male.equalsIgnoreCase("john"); true

int negative = male.compareTo(female); -3


int zero = male.compareTo("John"); 0
int positive = female.compareTo(male); 3
boolean notTrue = male.isEmpty(); false

- 42 -
String methods

A String literal such as "Hello" is also a String object on


which you can call these methods:
char ch = "François Englert won a Nobel Price".charAt(0);

String variables and literals can be concatenated using


the + operator

String greeting = "Hello";


String message = greeting + " Duke!";

Hello Duke!

- 43 -
Quiz: what is the output?

String me = "me";
int number = 2 + 3;
String result = me + " a ";
result += number + "!";
System.out.println("Give " + result);
System.out.println(3 + 7 + " hello world " + 3 + 7);

- 44 -
Quiz: Strings are immutable
•What is the output of the following code?

String s1 = "abc";
s1.concat("def");
System.out.println(s1);
String s2 = s1.concat("def");
System.out.println(s2);

Better se StringBuilder (see later)

- 45 -
Memory allocation for Strings

String one = "abc";


String two = "abc";
String three = new String("abc");

Stack Heap

ha t!?
one
a i t,w
"abc" W
two

three "abc"

- 46 -
Comparing Strings

String one = "abc";


String two = "abc";
String three = new String("abc");

System.out.println(one == two); true


System.out.println(one == three); false
System.out.println(two == three); false

System.out.println(one.equals(two)); true
System.out.println(one.equals(three)); true
System.out.println(two.equals(three)); true

- 47 -
Strings

• Conclusions and summary


– Strings can’t be modified
– String literals are allocated in memory only
once
– NEVER compare strings using ==
– Instead, compare using equals()

Common Programming Error 14.1 (page 623)

- 48 -
Exercises
•Ex 04.03-04.05

- 49 -
The StringBuilder class 14.4

•is an alternative to the String class:


– Its contents can be modified. You can append,
insert and remove text without new objects
being created all the time
– This makes it more performant and reduces
memory usage when a string is changed often

- 50 -
Creating String vs StringBuilder 14.4.1

•Two ways to create a String:


1. String literalString = "stringliteral";
2. String objectString =
new String("stringliteral");

Exp icit y declare as a


new object

•A StringBuilder object can only be created by


using one of its constructors
1. StringBuilder emptyBuilder = new StringBuilder();
2. StringBuilder builder =
new StringBuilder("stringliteral");

- 51 -
Methods of StringBuilder 14.4

•StringBuilder

•Some common methods


append(…): Appends the argument to the end of the StringBuilder
toString(): Returns the value of the StringBuilder as a String
object
length(): Returns the length of the StringBuilder
charAt(int index): Returns the char at position index (first one at
0)
reverse(): Reverses the content of the StringBuilder
•More methods: insert, setCharAt, deleteCharAt, replace,
subString, indexOf,…

- 52 -
Methods of StringBuilder: examples

StringBuilder spoon = new StringBuilder("spoon");


StringBuilder fork = new StringBuilder();
fork.append('f');
Builder pa er : append returns
fork.append('o'); the modified String ilder

fork.append('r').append('k');
System.out.println(spoon + " and " + fork);
spoon and fork

StringBuilder builder = new StringBuilder("builder");


builder.reverse();
System.out.println(builder); redliub

- 53 -
Exercises
•Ex 04.06-04.10

- 54 -
Formatting
Formatting data 2.4

• For displaying on the screen


System.out.printf("formatstring", variable, ...);
System.out.format("formatstring", variable, ...);

System.out.printf("%d apples are €%.2f.\n", 4, 14.0/4);


// Output: 4 apples are €3,50.

Yo can use both printf or format, both methods are identical (except or their name)

• When you need the result in a String object:


String.format("formatstring", variable, ...);
String str = String.format("%d apples are €%.2f.", 4, 14.0/4);
System.out.println(str);
// Output: 4 apples are €3,50.

- 56 -
Formatting data

Format specifiers (by default aligned to the right):


• %d for int and long (integer number)
• %f for float and double (decimal number)
• %s for String
• %c for char
• %b for boolean
• %n for a newline (more platform independent than \n)

Extra indicators between % and the type (t, f, s, ...)


• n specify the minimum number of positions (i.e. %20s)
• - (minus) indicates align to the left (i.e. %-20s)
• n.d when used with %f indicates the (total) minimum
amount of positions and the amount of decimals (e.g.
%6.2f), always automatically rounds to nearest
• , when used with numbers indicates a thousands separator
(e.g. %,d)
Formatter (complex)
- 57 -
Formatting data

Requirement: For every format specifier, there has


to be a parameter present of the corresponding
type.

System.out.printf("The %dth letter is %c\n", 5, 'e');


The 5th letter is e

double sum = 164.525;


String s = String.format("€%.2f %d%% VAT incl.", sum, 21);
System.out.println(s);

€164,53 21% VAT incl. % character adde as %%

a tomatic rounding

- 58 -
Quiz: what is the output?

System.out.printf("%b %c %d %f %s%n"
, true, 'X', 1, 3.14, "abc");

true X 1 3,140000 abc

double value = 1.35798642;


System.out.printf("%10.8f%n", value); 1,35798642
System.out.printf("%10.6f%n", value); 1,357986
System.out.printf("%10.4f%n", value); 1,3580
System.out.printf("%10.2f%n", value); 1,36
System.out.printf("%.1f%n", value); 1,4

- 59 -
Quiz: what is the output?

System.out.format("%4d%n", 1); 1
System.out.format("%4d%n", 12); 12
System.out.format("%4d%n", 123); 123
System.out.format("%4d%n", 1234); 1234
System.out.format("%4d%n", 12345); 12345
System.out.format("%4d%n", 123456); 123456

System.out.format("%-10s%n", "Paris"); Paris


System.out.format("%-10s%n", "Madrid"); Madrid
System.out.format("%-10s%n", "London"); London
System.out.format("%-10s%n", "Berlin"); Berlin

String city = "Antwerp";


System.out.printf("%-11s!%n", city); Antwerp !

How many spaces?


- 60 -
Exercises
•Ex04.11: Random seed

- 61 -
Review
1. Introduction
• Objects, messages, classes
2. Working with objects
• Creating, using and deleting objects
3. Simple objects
• Classes String and StringBuilder
4. Formatting
• Methods printf and format

- 62 -

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy