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

Lecture 3 - Intro to Classes _ Objects in Java

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

Lecture 3 - Intro to Classes _ Objects in Java

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

Vietnam National University of HCMC

International University
School of Computer Science and Engineering

Classes & Objects in Java


(IT069IU)

Le Duy Tan, Ph.D.


📧 [email protected]

🌐 leduytanit.com

1
Previously,
We talked about:
- Different Java Platforms
- Our choice of JDK
- The best IDE selections
- Create the first Java programs
- Compile and Run with commands or on IntelliJ
- Java data types:
- Primitive
- Non-primitive (reference types)
- Variable
- Operators

2
Agenda
- Useful Classes
- Scanner
- Read input string with nextLine(), next()
- Read input number with nextDouble()
- String
- Display string with print(), println(), printf()
- Math
- pow(), max(), random()
- Primitive vs Reference
- Class
- Attributes
- Method with Parameters
- Getters and Setters Methods
- Access Modifiers (Public & Private)
- Constructor with Parameters
- UML Diagram
- Object
- Create objects from class with keyword new
- Call methods with input arguments
- Bank account application example
3
Helpful Classes
Reference Types = Objects

4
Scanner Class: Reading Inputs
- API documentation (http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html)
- To use Scanner class, remember to import java.util.Scanner
- Can read from different input sources: input keyboards, files, …
- Can convert inputs to different type of data types: string, byte, short, int, float, double, …

Java naming convention Method


names – lowerCamelCase

5
Scanner Class: Demo
TestScanner.java

[Question] Can you figure out the


difference between println() and
print()? next() and nextLine()?
Scanner: nextLine() vs next()
- nextLine() method:
- Reads characters typed by the user until the newline character is encountered.
- Returns a String containing the characters up to, but not including the newline.
- Press Enter to submit the string to the program. After that, it inserts a newline
character at the end of the characters the user typed.
- The newline character is not included in the input string.
- next() method
- Reads individual words until a white-space character is encountered, then
returns a String, but not including the white-space.
- Information after the first white-space character can be read by other
statements that call the Scanner’s methods later in the program-.

7
Display Output (System.out)
- System.out.print method displays an output string.
- Unlike println, print does not position the output cursor at the beginning of the
next line in the command window.
- The backslash (\) is an escape character
Escape sequence Description

\n Newline character. Example: “My name\nis James”. My name


is James

\t Horizontal Tab character. Example: “My name\tis James” My name is James

\\ Backslash character. Example: “My name \\ is James” My name \ is James

\” Double quote. To print a double quote in a string like:


System.out.println(“ \”my \” example\” ”) “my “ example”
8
Print vs Println Example

9
Escape Character Example

10
Display Output Formatted Text with printf

- System.out.printf method.
- f means “formatted” to displays formatted data

- Format specifiers begin with a percent sign (%) and are


followed by a character that represents the data type.
- %s is a placeholder for string.
- %d is a placeholder for integer. (byte, short, int, long,..).
- %f is a placeholder for floating number (float or double)

11
Printf Example
public class PrintfExample {
public static void main(String[] args) {
System.out.printf("First: %s", "Hi there!");
System.out.printf("Second: %s\n%s.\n", "Welcome to", "IU Uni!");
System.out.printf("Third: %s %s\t%d\n", "Have fun", "with Java!", 123);
System.out.printf("Last: %f %.2f", 3.12345, 3.12345);
}
}

Output:

First: Hi there!Second: Welcome to [Question] What does this print?


IU Uni!. System.out.printf("%s\n%s\n%s\n", "*", "***",
Third: Have fun with Java! 123 "*****");
Last: 3.123450 3.12
12
String Class: Representation in Text
- API documentation (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html)

13
String Class: Demo 1
TestString.java

[Question 1] Can you figure out what is the


purpose of:
- length()
- charAt(5)
- substring(5, 8)
- indexOf(“in”)
- + between two strings
- equals

[Question 2] Why do we use .equals() instead


of == to compare strings?
14
String Class: Comparing strings
- As strings are objects, do not use == if you want to check if two strings
contain the same text
- Use the equals() method provided in the String class instead.

Scanner sc = new Scanner(System.in); If both of inputs are:


System.out.println("Enter 2 identical strings:"); Tom
String str1 = sc.nextLine(); Tom
String str2 = sc.nextLine();
System.out.println(str1 == str2);
Question:
System.out.println(str1.equals(str2));
Can you guess what is
System.out.println(str2 == str2);
the output of the
System.out.println(str2.equals(str2));
program?
15
Primitives vs References
Primitive types are basic Java types
- int, long, double, boolean, char, short, byte, float.
- A variable stores the actual value of that type.

Non-primitive types are Reference types


- String, Array, Class Objects, …
- A variable stores only the reference (memory address
location) to point to the actual object.

16
How java stores primitive values
- Variables are like fixed size cups.
- Primitives are small enough that they just fit into the cup.
- In other words, the variable stores directly the value of that data.

17
Variable
How java stores objects
- Objects are too big to fit in a variable
- The actual object is stored somewhere else in the memory.
- The variable stores only the reference (memory address) which points to the
actual object.

Variable Variable

18
References
- The object’s location is called a reference
- == operator only compares the references (memory address)

String string1 = new String(“IU is the best uni”);


String string2 = new String(“IU is the best uni”);

Does string1 == string2?

Car car1 = new Car(“Green”, 2020);


Car car2 = new Car(“Green”, 2020);

Does car1 == car2?


19
References
String string1 = new String("IU is the best uni"); [Question] What is the output?
String string2 = new String("IU is the best uni");

System.out.print(string1 == string2);

“IU is the best uni”

“IU is the best uni”

string1 string2 20
Update References
String string1 = new String("IU is the best uni"); [Question] What is the output?
String string2 = new String("IU is the best uni");

string1 = string2; // update the reference

System.out.print(string1 == string2);

Reference “IU is the best uni”

“IU is the best uni”


21
string1 string2
Math Class: Performing Computation
- API documentation (http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html)
- 2 class attributes:
- E
- PI

22
Math Class: Demo
TestMath.java

[Question] What is the output range


of Math.random() ?

[Question] How to generate a


random number between 0 and 10?

[Question] Does Math.random()


really generate a true random
number?
23
https://www.baeldung.com/java-generating-random-numbers-in-range
"Tell us what the future holds, so
we may know that you are gods."
Isaiah 41:23

24
Math.random() is pseudo random number generator (PRNG)

- Using algorithm with an input seed to generate a sequence of numbers that


approximates randomness.
- Pseudo random because it is not possible to generate truly random from
deterministic thing like computer.
To make the randomness reproducible:

seed number 1 PRNG function random sequence 1

seed number 2 PRNG function random sequence 2

To make the randomness not reproducible:

default seed Nearly truly random


(current date time) PRNG function
sequence

https://www.delftstack.com/howto/java/set-random-seed-in-java/ 25
https://www.journaldev.com/17111/java-random
PRNG Applications
Monte Carlo Simulation

Machine Learning & Deep Learning

26
Class & Object

27
GradeBook Class
GradeBook.java

28
Explanation for GradeBook Class
- Create a new class, GradeBook, as a template to create objects of that type latter.
- Each class declaration that begins with keyword public must be stored in a file
that has the same name as the class and ends with the .java file-name extension.
- Keyword public is an access modifier.
- Indicates that the class is “available to the public”
- The return type specifies the type of data the method returns after performing its
task.
- Return type void indicates that a method will perform a task but will not return
(i.e., give back) any information to its calling method when it completes its task.
- Cannot execute Class GradeBook because it does not contain main method.
- Otherwise will receive an error message like:
- Exception in thread "main" java.lang.NoSuchMethodError: main
29
GradeBookTest Class with main method
GradeBookTest.java

30
Explanation for GradeBookTest Class
- Public static void main(String args[]) is the entry (starting) point of the whole
project which is compulsory.
- To help you prepare for the larger programs, use a separate class
(GradeBookTest) containing method main to test each new class.
- Some programmers refer to such a class as a driver class.
- The main method is called automatically by the Java Virtual Machine (JVM)
when you execute an application.

31
Class Objects Creation
- Class objects can be created from a class:
- Keyword new creates a new object of the class.
- The parentheses to the right of the class name are required.
- Parentheses in combination with a class name represent a call to a
constructor, which is similar to a method but is used only at the time
an object is created to initialize the object’s data.
- In other words, it instantiates a class by allocating memory for a new
object and returning a reference to that memory.

32
Call Methods of an Class Object
- Call a method via the class-type variable
- Variable name followed by a dot separator (.), the method name and
parentheses.
- Call the method to perform its task.
- Any class can contain a main method.
- The JVM invokes the main method only in the class used to execute
the application.
- If multiple classes that contain main, then one that is invoked is the
one in the class named in the java command.

33
UML (Unified Modeling Language)
- A diagram where people describe the design of the projects by showing the
classes, their attributes, methods, and the relationships among those objects.
- Each class is modeled in a class diagram as a rectangle with three
compartments.
- Top: contains the class name centered horizontally in boldface type.
- Middle: contains the class’s attributes, which correspond to instance variables.
- Bottom: contains the class’s operations, which correspond to methods.
- Access Modifiers: (+) means public and (-) means private.

Class Name

Attributes

Methods

34
UML class diagram for GradeBook
GradeBook.java

35
Method Parameter
- Car analogy
- Pressing a car’s gas pedal sends a message to the car to perform a task—make
the car go faster.
- The farther down you press the pedal, the faster the car accelerates.
- Message to the car includes the task to perform and additional information that
helps the car perform the task.
- Parameter: Additional information which a method needs to perform its task.

- A method can require none, or one, or more


parameters.
- A method call provide values for those
parameters, we call them arguments.
36
A Method with a Parameter
GradeBook.java

UML Diagram for GradeBook Class


[Question] Have you noticed any difference
between this Gradebook class UML with the
previous one?
37
GradeBookTest.java

Output:

38
Import
- Classes System and String are in the package java.lang:
- Implicitly imported into every Java program.
- Can use the java.lang classes without explicitly importing them.
- Most other classes you’ll use must be imported explicitly.
- A package in Java is used to group related classes. Think of it as a folder in a file directory. We use
packages to avoid name conflicts, and to write a better maintainable code.
- Classes that are compiled in the same directory on disk are in the same package—known as the
default package.
- Classes in the same package are implicitly imported into classes of other files in the same
package.
- An import declaration is not required if you always refer to a class via its fully qualified class name
- Package name followed by a dot (.) and the class name.

Import only Scanner class and use that imported class: Import the whole java.util package including Scanner class:

No import and use the fully qualified class name of Scanner:

https://docs.oracle.com/javase/7/docs/api/java/lang/package-summary.html 39
https://www.w3schools.com/java/java_packages.asp
Instance Variables
- A class normally consists of one or more methods that manipulate
the attributes that belong to a particular object of the class.
- Attributes (fields) are represented as variables in a class declaration
- Declared inside a class body but outside the bodies of methods.
- Instance variable
- When each object of a class maintains its own copy of an attribute (field/instance
variable).

40
Access Modifiers
- Attributes (data) and Methods (behavior) are members of an object.
- The access to members of an object can be controlled (Data Hiding)
- Public: Those members can be anywhere.
- Private: Those members can be only within the class.
- No restrictions on member access is a bad OO designed.

41
Access Modifier

42
Private Attributes, Getters & Setters Methods
- Instance variables (attributes) should be private (data hiding or
information hiding) and methods to be are public.
- Private variables are encapsulated (hidden) in the object and only are accessible only
to methods of the class.
- Prevents instance variables from being modified accidentally by a class in another
part of the program.
- Set and get methods:
- Setters: methods to change the values of (private) variable
- Getters: method used to access the values of (private) variables.
- Sometimes, methods can be private only they are only needed to be accessed by
other methods of the same class. (helper methods)

43
Attributes (Fields) in GradeBook Class
GradeBook.java

44
Output:
GradeBookTest.java

[Question]
- Why is the course name is null at the
beginning?
- Is there any way to set variable value of
an object right away when creating it?

45
Constructors in a Class
- A constructor is called when we use the keyword new to create a new object.
- Keyword new requests memory from the system to store an object, then calls the
corresponding class’s constructor to initialize the object.
- Java requires a constructor call for every object that is created.
- Without providing your constructor, a class will have a default constructor with no
parameters.
- All variables will be initialized to be default values when that object is created.
- With your own constructors:
- A constructor of a class can set variable values as input arguments when the
object is created.
- A constructor is a special public method, which must have the same name as the class.

46
Constructor in a Class
GradeBook.java

47
GradeBook.java

48
GradeBookTest.java

49
Bank Account Application Example
Write Two Classes:

- Account:
- An attribute named “balance” to store money value (double type)
- A constructor to initialize account object with parameter “initialBalance” value.
- Make sure the initial balance number is only positive number; otherwise it is 0.
- Two methods:
- credit: take an amount as a parameter to add that amount to current balance of that account.
- getBalance: return the current value of the balance of that account.
- AccountTest:
- Create two test Account Objects:
- account1 with initial balance to be 50.00
- account2 with initial balance to be -7.53
- Display the balances of those two new accounts after being initialized.
- Take amount values from user inputs to be added to the balances of the account1 and account2.
- Display the balances of those two accounts before and after being added new amounts.
50
Account.java

51
AccountTest.java

52
AccountTest.java

53
AccountTest.java

54
Homework: 649 Lotto Lottery!
- A lottery ticket is $4.
- A ticket having 6 different numbers (from 1 to 49) (Can be repeated)
- On a Saturday, they draw the lottery, and the winning numbers are:

11, 43, 24, 30, 60, 43

- Match at each position:


- Match One or Two numbers to get a small prize. ($10)
- Match Three numbers to get a small prize. ($100)
- Matching Four numbers gets a bigger prize. ($1000)
- Matching Five is even bigger. ($5000)
- Matching ALL SIX of the numbers you might win millions. ($5 million in cash)
- In the example, we got matches at position 1, 3, 4, 6 (4 numbers) = $1000
- [Math Question] What is the possibility of you winning by matching all 6 numbers?
- Homework Task:
- Write a simple program allows you to buy a ticket with six random numbers, and generate
the winning numbers and return what kind of prize you won (one game).
- Bonus: imagine you buy up to 100,000 tickets, can you figure out if you actually profit or 55
loss in a long run? mathsisfun.com/data/lottery.html
Examples of The Basic 649 Lottery Program
Here is just an example of an implementation of 649 Lottery, you can try
something different:
- Generate a winning ticket with 6 numbers (from 1 to 49)
- Generate a user ticket (either generate randomly or let them enter those
numbers)
- Try to find out how many numbers are the same.
- Based on number of matches, calculate the reward money for the user.

56
Bonus Task for 649 Lottery
- We want to figure out if we should play lottery for a long term to
actually profit some money!

You will need to use loop (for or while loop) [Bonus Homework] Can you figure out
which we will learn more next week.
the ? numbers for 100,000 games?
https://www.w3schools.com/java/java_for_loop.asp

https://www.w3schools.com/java/java_while_loop.asp 57
Submission for 649 Lottery Homework
- The submission file (one single zip file) should contains:
- Screenshots of the interaction outputs (Like my examples).
- All *.java files of the projects.
- A readme txt file to explain about:
- The project
- How to use it?
- Is there any interesting new feature of it?
- The file must be submitted on the blackboard.
- Bonus Tasks:
- Bonus tasks to calculate the statistics of playing many games.
- An UML image for class diagrams for your project.

58
Recap
This lecture, we have learnt about:
- Useful Classes
- Scanner
- Read input string with nextLine(), next()
- Read input number with nextDouble()
- String
- Display string with print(), println(), printf()
- Math
- pow(), max(), random()
- Primitive vs Reference
- Class
- Attributes
- Method with Parameters
- Getters and Setters Methods
- Access Modifiers (Public & Private)
- Constructor with Parameters
- UML Diagram
- Object
- Create objects from class with keyword new
- Call methods with input arguments of the object
- Bank account application example
59
Thank you for your listening!

“One who never asks


Either knows everything or nothing”
Malcolm S. Forbes

60

You might also like