Lecture 3 - Intro to Classes _ Objects in Java
Lecture 3 - Intro to Classes _ Objects in Java
International University
School of Computer Science and Engineering
🌐 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, …
5
Scanner Class: Demo
TestScanner.java
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
9
Escape Character Example
10
Display Output Formatted Text with printf
- System.out.printf method.
- f means “formatted” to displays formatted data
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:
13
String Class: Demo 1
TestString.java
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)
System.out.print(string1 == string2);
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");
System.out.print(string1 == string2);
22
Math Class: Demo
TestMath.java
24
Math.random() is pseudo random number generator (PRNG)
https://www.delftstack.com/howto/java/set-random-seed-in-java/ 25
https://www.journaldev.com/17111/java-random
PRNG Applications
Monte Carlo Simulation
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.
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:
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:
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!
60