Lec 1. Introduction To OOP in Java (Cont)
Lec 1. Introduction To OOP in Java (Cont)
UET, VNU HN
Contents
Java programming language
Classes
Fields/attributes
Methods
Access modifiers
Constructors
08/09/2023 Page 2
Why you need to learn java
games)
08/09/2023 Page 3
Brief history
1991: developed by Sun Micrsoft as a programming language for
embedded environments
Oak was the first name of Java
Java 1.0.2, 1.1
“Write ONCE, run ANYWHERE”
Slow
Used in web applications (applets)
Java 2 (version 1.2 – 1.4)
Fast & more powerful
3 platforms: J2ME, J2SE, J2EE
Java 5,6,7 (version 1.5…)
Much more upgraded!
08/09/2023 Page 4
Structure of a java program
08/09/2023 Page 5
Compile
08/09/2023 Page 6
Compile
Java source code is
compiled into
bytecode
Bytecode is platform
independent
Bytecode is executed
by JVM (Java Virtual
Machine)
08/09/2023 Page 7
JVM
JVM is platform dependent (hardware, OS)
Ensure java program (bytecode) can execute on different platforms (i.e.
platform independent)
Guarantee security
It’s included in JDK (Java Development Kit)
08/09/2023 Page 8
Java applications
Mobile applications
Card applications
08/09/2023 Page 9
Example
Same as class
HelloWorld.java: name
Class Class name
public class HelloWorld {
main() method
public static void main (String[] args) {
08/09/2023 Page 10
Compile & run
Compile HelloWorld.java
javac HelloWorld.java
public class HelloWorld {
Run
public static void main (String[] args)
java HelloWorld {
System.out.println("Hello, world");
}
}
compiler
HelloWorld.class
08/09/2023 11
More than two classes
2 classes in different files
08/09/2023 12
Compile & run
Compile
javac TestGreeting.java
Greeting.java automatically translated
Run
java TestGreeting
08/09/2023 13
JDK – Java Development Kit
Java application development environment
Main components
javac compiler, converts source code into Java bytecode
08/09/2023 14
main() Method
08/09/2023 Page 15
Define a class
Syntax
[public] class class_name {
...
}
E.g.,
class MyDate {
….
}
08/09/2023 16
Constructors
• Default constructor
• Parameterized constructor
• Copy constructor
• Accessing constructor
• Multiple constructors & self-reference
Constructors
Constructors are special types of methods that are responsible for
creating & initializing an object of that class
08/09/2023 Page 18
Default constructor
is one that does not takes any input parameters
it’s optional, which means if you don’t create a default constructor Java will
automatically assume there’s one by default that doesn’t really do anything
08/09/2023 Page 19
Default constructor…
However, if the class has fields that need to be initialized before the object can be
used, then you should create one that does so
E.g.,
class Game {
int score;
//default constructor
Game(){ score=0; //initialize the score; or you can let it empty }
}
08/09/2023 Page 20
Parameterized constructor
A constructor can also take input parameters
e.g., assume that some games starts with a positive score value and not just 0,
that means we need another constructor that takes an integer parameter as an
input, and uses it to initialize the score variable
class Game {
int score;
//default constructor
Game(){
score=0;//initialize the score
}
Game(int startingScore){
score=startingScore;
}
}
08/09/2023 Page 21
Parameterized constructor…
However….
class Game {
int score;
//default constructor
Game(int startingScore){
score=startingScore;
}
} Game g1 = new Game ();//error
Game d2 = new Game(10);
08/09/2023 Page 22
Constructors
Accessing constructor
Unlike normal methods, constructors cannot be called using the dot ‘.’ modifier,
instead every time you create an object variable of a class type the
appropriate constructor is called
To create an object of a certain class, we use the new keyword followed by the
constructor we want to use
E.g.
08/09/2023 Page 23
Constructors
Accessing constructor…
If you don’t initialize an object using the new keyword, then its value will be set
to something called null
Game o = null;
In some case, you want to set an object to null to indicate that such object is
invalid or yet to be set
08/09/2023 Page 24
Why multiple constructors
WHY still need to keep the default constructor now that we have another
constructor that can create, say a game object with any starting score
value (including 0)?
Then, you can add extra parameterized constructors that allow more
customization when dealing with less common cases
08/09/2023 Page 25
Self reference
Sometimes you need to refer to an object within one of its methods or constructors,
to do so we use the keyword this
The most common reason for using this keyword is because a field has the same name as a
parameter in the method or constructor
class Position {
int row=0;
int column=0;
Position(int r,int c){
row=r; column=c;
}
}
08/09/2023 Page 26
Self reference…
A more readable way would be use the same names for the constructor
parameters
Need to use the this keyword to separate the fields and the parameters
class Position {
int row=0;
int column=0;
Position(int row, int column){
this.row=row; this.column=column;
}
}
08/09/2023 Page 27
Example
Contact manager
class Contact{
String name;
String email;
String phoneNumber;
}
no methods, since a contact object itself won’t be “doing” much attention
Next, create the class that store an array of contacts and is in charge of adding or searching
for contacts
class ContactsManager{
Contact[] myFriends;
int friendCount;
//construtor
//add a contract
//search a contact
}
08/09/2023 Page 28
Example
Contact manager…
class ContactsManager{
Contact[] myFriends;
int friendCount;
ContactsManager(){
this.FriendCount=0;
this.myFriends = new Contact[100];
}
….
}
The friendCount starts from 0 and will increment every time we add a new
contact later
08/09/2023 Page 29
Example of Contact manager…
Class methods
The method addContact() will add a Contact object to the Contact array
myFriends
Takes a Contact object as an input parameter
Use friendCount value to fill that slot in the array with the contact that was passed into
the method
friendCount++;
08/09/2023 Page 30
Example of Contact manager…
Class methods
Now, add another method searchContact () that will search through the
array using a name String and return a Contact object once a match is
found
08/09/2023 Page 31
run the program
class Main{
public static void main(String [] args){
ContactManager myContactManager= new ContactManager();
08/09/2023 Page 32
Copy constructor
Besides two types of constructors introduced, a class object can be
initialized with another previously created object of the same
class
public Game(Game g) {
score = g.score;
}
}
08/09/2023 33
Access modifiers
08/09/2023 Page 35
Access modifiers
08/09/2023 Page 36
Access modifiers
class Book{
private String title
private String author
public boolean isBorrowed;
public Book(String title, String author){
this.title = title; this.author=author;
}
}
We can do book.isBorrowed = true anywhere in the project
However, it’s still risky, we may end up mistakenly setting the boolean to true when we only
mean to check if it is true or false
08/09/2023 Page 37
Access modifiers
class Book{
private String title
private String author
private boolean isBorrowed;
public Book(String title, String author){
this.title = title; this.author=author;
}
public void setTitle(String title){ this.title = title;} //setter
public String getTitle(){ return title;} //getter
….
}
08/09/2023 Page 38
Access modifiers
08/09/2023 Page 39
Access modifiers
08/09/2023 Page 40
Methods (public vs private)
since they can only be seen and called by the same class
used to organize your code and keep it simple and more readable
Public methods are the actual actions that the class can perform
08/09/2023 Page 41
Methods (public vs private)
class Person{
Methods (public
private String vs private)
userName;
private String SSN;
private string getID(){return SSN + “-” + userName;}
public getUserName(){return userName;}
public boolean isSamePerson(Person p){
if(p.getID().equals(this.getId()) return true;
else return false;
}
}
Method getID() was set to private so that no other class can know the social security
number of any person
can use it internally only to compare this person with another person
08/09/2023 Page 42
public classes
Classes can be labeled public or private
if you don’t use any label, it will default to something called “package
public”
that means, you’ve labeled them public but only to the classes that are in the
same package/folder
08/09/2023 Page 43
Conclusion
Always try to declare all fields as private
Create a public method that set each private field, this way you will know when
you are changing a field
Create a public method that returns each private field, so you can read
the value without mistakenly changing it
08/09/2023 Page 44