
Classes and
Objects in Java
Object-oriented programming

Classes and objects in Java 2
Đ i h c Công ngh . ĐHQG Hà N iạ ọ ệ ộ
Outline
Classes
Working with objects
Attributes, methods, and access control
Constructors
Readings:
Java how to program, chapter 3, 8

Classes and objects in Java 3
Đ i h c Công ngh . ĐHQG Hà N iạ ọ ệ ộ
Java program
A Java program is a collection of objects
Each class is specified in one source file
(file name is the same with class name)
Every line of code you write in Java must be
inside a class (not counting import directives)
Increase modularity
Easier to modified code, shorter compile time
3

Classes and objects in Java 4
Đ i h c Công ngh . ĐHQG Hà N iạ ọ ệ ộ
// GradeBook.java
public class GradeBook
{
// display a welcome message to the GradeBook user
public void displayMessage()
{
System.out.println( "Welcome to the Grade Book!" );
}
} // end class GradeBook
// GradeBookTest.java
public class GradeBookTest
{
// main method begins program execution
public static void main( String args[] )
{
// create a GradeBook object and assign it to myGradeBook
GradeBook myGradeBook = new GradeBook();
// call myGradeBook's displayMessage method
myGradeBook.displayMessage();
}
} // end class GradeBookTest
Welcome to the Grade Book!
class declared as public must be
stored in a file with the same name
class declaration
begins / ends
main() is called automatically by
the Java Virtual Machine when
the program is executed
02 classes
in 02 files
creates an instant / object of the class
myGradeBook is the reference to it

Classes and objects in Java 5
Đ i h c Công ngh . ĐHQG Hà N iạ ọ ệ ộ 5
Objects
Objects are manipulated via references
Object references play the roles similar to pointers
Objects must be explicitly created by new operator
5
public class GradeBookTest
{
// main method begins program execution
public static void main( String args[] )
{
// create a GradeBook object and assign it to
myGradeBook
GradeBook myGradeBook = new GradeBook();
// call myGradeBook's displayMessage method
myGradeBook.displayMessage();
}
} // end class GradeBookTest

