You are on page 1of 25

Introduction to Classes and

Objects
Ridwan Rismanto, S.ST
Declaring Class
• GradeBook class
– Display a welcome message
– Receive course name as an argument and displaying
it as the part of welcome message
– Store the course name in GradeBook object
– Using methods to set and obtain the course name
– Initialization using constructor
• GradeBookTest class
– Has the main method to use GradeBook class
Declaring Class (2)
• 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 .java extension.
GradeBook class
GradeBookTest class
Inside the GradeBook class
• Keyword public is an access modifier
• Keyword void indicates that a method
doesn’t have a return value
• Class GradeBook isn’t an application
because it doesn’t have a main method
– It will be error if you try to execute
Inside the GradeBookTest class
• This class is an application because it has main
method that will be executed first by the JVM
• The main method is special because it is static
– Allows us to call the method without creating an
object
• In this application, we call GradeBook’s
displayMessage method.
– Keyword new creates a new object of the class
• The object’s method can be called using dot
separator (.)
UML
• Graphical representation scheme for
modelling object oriented systems
– Class name
– Class attributes
– Class operations (methods)
UML for GradeBook class
Class GradeBook declaration with
one method that has a parameter
Class GradeBookTest with
parameter passing
Output
Inside the GradeBookTest class
• A scanner named input for reading the
coursename from user
• A variable passing
– From user’s input to variable nameOfCourse
– And then passing it to displayMessage
method
Updated UML for GradeBook class
Instance Variables, set Methods
and get Methods
• A Class normally consists of methods and
attributes
• Attributes are represented as variables in
a class declaration
GradeBook Class with an Instance Variable,
a set Method and a get Method
GradeBookTest Class That
Demonstrates Class GradeBook
Output
Access Modifiers
• Declaring instance variables with access
modifier private is known as data hiding
– variable courseName is encapsulated (hidden) in the
object and can be accessed only by methods of the
object's class
• Private
– Can only be accessed by methods that is a member
of the class
• Public
– Can be accessed by methods outside the class
Updated UML for GradeBook class
Initialing Objects with Constructors
• Each class we declare can provide a constructor
– A method that will be executed first when we create
an object
– Java automatically provides default constructor in any
class
• Constructor must have the same name as the
class
• Usage example : we want to define a default
values for our class’s attributes
GradeBook class with a constructor that
receives a course name
Constructor used to initialize GradeBook
objects
Updated UML for GradeBook class

You might also like