Title: Introduction to Classes and Objects
1Introduction toClasses and Objects
2- public class GradeBook
-
- // display a welcome message
- public void displayMessage()
-
- System.out.println(Welcome to the
Grade Book!) -
3public class GradeBookTest public static
void main(String args )
// create GradeBook object GradeBook
myGradeBook new GradeBook() //
call the objects display method
myGradeBook.displayMessage()
4Compiling
- To compile the GradeBook
- javac GradeBook.java
- javac GradeBookTest.java
- or
- javac GradeBook.java GradeBookTest.java
- or
- javac GradeBookTest.java GradeBook.java
- or
- javac GradeBookTest.java // automatically
compiles GradeBook.java - or
- javac .java // compiles all .java files in
the directory
5Compiling
- If there are multiple files, you can also list
them in a file, and send the file to javac - javac _at_myfiles
GradeBookTest.java GradeBook.java
myfiles
6UML
GradeBook
Name of class
Attributes
displayMessage()
Method name
means public
7public class GradeBook // display a
welcome message public void
displayMessage( String courseName )
System.out.printf(
Welcome to the Grade Book for s\n,
courseName)
8import java.util.Scanner public class
GradeBookTest public static void
main(String args )
Scanner input new Scanner(System.in)
// create GradeBook object
GradeBook myGradeBook new GradeBook()
System.out.println(Please enter the course
name) String nameOfCourse
input.nextLine() System.out.println(
) // call the objects display
method myGradeBook.displayMessage(nam
eOfCourse)
9UML
GradeBook
displayMessage(courseName String)
Parameter
10Imports
- Why did we need to import class Scanner, but not
class System, String, or GradeBook? - System and String are in package java.lang, which
are imported to every Java program. - Classes in the same directory can be used without
importing. - Such classes are considered to be in the same
package, known as the default package.
11Imports
- We need not import java.util.Scanner if we
provide the full package and class name each time
we use it. - If it is imported, we can refer to it as simply
Scanner. - If it is not imported, we must refer to it
everywhere as java.util.Scanner. - Most programmers do not wish to use the full
name, so importing is done.
12Instance Variables
- A class defines attributes, called fields.
- Each object has its own copy of these attributes,
called instance variables.
object
class
Bob 24
public class Person String name int
age
Fields (attributes)
object
Sue 23
13- // Fig. 3.7 GradeBook.java
- // GradeBook class that contains a courseName
instance variable - // and methods to set and get its value.
- public class GradeBook
-
- private String courseName // course name for
this GradeBook - // method to set the course name
- public void setCourseName( String name )
-
- courseName name // store the course name
- // end method setCourseName
- // method to retrieve the course name
- public String getCourseName()
-
- return courseName
- // end method getCourseName
14- // Fig. 3.8 GradeBookTest.java
- // Create and manipulate a GradeBook object.
- import java.util.Scanner // program uses Scanner
- public class GradeBookTest
-
- public static void main( String args )
-
- // create Scanner to obtain input from
command window - Scanner input new Scanner( System.in )
- // create a GradeBook object and assign it
to myGradeBook - GradeBook myGradeBook new GradeBook()
- // display initial value of courseName
- System.out.printf( "Initial course name is
s\n\n", myGradeBook.getCourseName() ) - // prompt for and read course name
- System.out.println( "Please enter the
course name" ) - String theName input.nextLine() // read
a line of text
15Access Modifiers
- Members of a class may or may not be seen outside
the class, depending on their access modifier. - If public, the member is seen outside the class.
- If private, the member is only seen inside the
class. - Methods are normally public, and represent the
interface to the object. - A method may be private if only needed by the
class itself. - Instance variables are normally private to
enforce data hiding (encapsulation). - This is desirable to protect the data, so that
only the object itself may change the data.
16class
public class Person private String name
private int age public displayMessage()
private formatMessage() ...
Fields are normally private.
Methods are normally public.
A method may be private if only used by the
object.
17Initial Values
- Fields are initialized to a default value.
- Local variables are not initialized.
- Fields of type Object are initialized to null.
- The next slide summarizes initialization of
fields.
18(No Transcript)
19Get and Set Methods
- Since private data members are hidden from
clients, a class may provide a method to get and
set each data member. - For courseName, the class provided
getCourseName() and setCourseName(). - This naming style is not required but is
recommended since JavaBeans expects such naming. - JavaBeans is a means of creating reusable
software components in Java.
20UML
GradeBook
- courseName String
Private
setCourseName(name String) getCourseName()
String displayMessage(courseName String)
Return type
21Primitive Types vs Reference Types
- As stated before, there are primitive types
(boolean, byte, char, short, int, long, float,
double) and reference types. - Everything that is a nonprimitive type is a
reference type. - Primitive types contain a particular value.
- Reference types refer to an object somewhere in
memory (or null).
22Constructors
- A default constructor is provided if none is
coded. - You can provide your own constructors to allow
for other initializations of objects.
23// Fig. 3.10 GradeBook.java, GradeBook class
with a constructor to initialize the course
name. public class GradeBook private String
courseName // course name for this GradeBook
// constructor initializes courseName with String
supplied as argument public GradeBook( String
name ) courseName name //
initializes courseName // end constructor
public void setCourseName( String name )
courseName name // store the course name
// end method setCourseName public String
getCourseName() return courseName
// end method getCourseName public void
displayMessage() System.out.printf(
"Welcome to the grade book for\ns!\n",
getCourseName() ) // end method
displayMessage // end class GradeBook
24// Fig. 3.11 GradeBookTest.java // GradeBook
constructor used to specify the course name at
the // time each GradeBook object is
created. public class GradeBookTest // main
method begins program execution public static
void main( String args ) // create
GradeBook object GradeBook gradeBook1 new
GradeBook( "CS101 Introduction to Java
Programming" ) GradeBook gradeBook2 new
GradeBook( "CS102 Data Structures in
Java" ) // display initial value of
courseName for each GradeBook
System.out.printf( "gradeBook1 course name is
s\n", gradeBook1.getCourseName() )
System.out.printf( "gradeBook2 course name is
s\n", gradeBook2.getCourseName() )
// end main // end class GradeBookTest
25UML
GradeBook
Constructor should be listed first in this section
- courseName String
constructor GradeBook(name String)
setCourseName(name String) getCourseName()
String displayMessage(courseName String)
left-pointing double angle quotation mark also
known as a guillement (pronounced gill-uh-met), a
French word
26Float Values
- Float values, unlike integer values, may have a
fractional value. - Java has two types for float values
- Float has 7 significant digits of precision
- Double has 15 significant digits of precision
- Appendix D in book gives ranges.
- By default, float literals are type double (just
like C). - Remember that float values will not be able to
exactly represent some numbers, such as 1/3.
27Float Value Formatting
- When using printf to print floats, instead of s
or d, use f. - .2f means print a float value with 2 places
after the decimal (rounded). - f is used for type float or double.
28// Fig. 3.13 Account.java // Account class with
a constructor to initialize instance variable
balance. public class Account private
double balance // instance variable that stores
the balance // constructor public
Account( double initialBalance ) //
validate that initialBalance is greater than 0.0
// if it is not, balance is initialized to
the default value 0.0 if ( initialBalance gt
0.0 ) balance initialBalance
// end Account constructor public void
credit( double amount ) // credit (add) an amount
to the account balance balance
amount // add amount to balance // end
method credit public double getBalance()
// return the account balance
return balance // gives the value of balance to
the calling method // end method
getBalance // end class Account
29import java.util.Scanner public class
AccountTest // Create and manipulate an Account
object. public static void main( String
args ) Account account1 new
Account( 50.00 ) // create Account object
// display initial balance of each object
System.out.printf( "account1 balance
.2f\n", account1.getBalance() )
// create Scanner to obtain input from
command window Scanner input new Scanner(
System.in ) double depositAmount //
deposit amount read from user
System.out.print( "Enter deposit amount for
account1 " ) // prompt depositAmount
input.nextDouble() // obtain user input
System.out.printf( "\nadding .2f to account1
balance\n\n", depositAmount )
account1.credit( depositAmount ) // add to
account1 balance // display balances
System.out.printf( "account1 balance .2f\n",
account1.getBalance() ) // end
main // end class AccountTest
30GUI
- Java supports creating a graphical user
interface. - The class JOptionPane provides dialog boxes to
display output.
31Output
import javax.swing.JOptionPane public class
Dialog1 public static void main(String
args ) JOptionPane.showMessageDia
log(null, Welcome\nto\nJava)
32Input
- JOptionPane also supports input through method
showInputDialog. - If the user cancels the dialog, the dialog
returns null.
33Input
import javax.swing.JOptionPane public class
NameDialog public static void main(String
args ) String name
JOptionPane.showInputDialog("What is your
name?") String message
"Hello " name
JOptionPane.showMessageDialog(null, message)
34End of Slides