Title: Chapter 3 Introduction to Classes and Objects
1Chapter 3 - Introduction to Classes and Objects
Outline3.1 Introduction 3.2 Classes,
Objects, Methods, and Instance Variables 3.3
Declaring a Class with a Method and
Instantiating an Object of a Class 3.4
Declaring a Method With a Parameter 3.5
Instance Variables, set Methods and get
Methods 3.6 Primitive Types vs. Reference
Types 3.7 Initializing Objects with
Constructors 3.8 Floating-Point Numbers and type
double
23.1 Introduction
- Previous chapter used simplest class
- one method (main) and no data
- Most applications use several classes to
accomplish program requirements - Very large industrial applications can have
thousands of classes - This chapter explores class basics
- Classes
- Objects
- Methods and constructors
- Instance variables
33.2 Classes, Objects, Methods, and Instance
Variables
- What is a class?
- A collection of data (attributes), plus
procedures that operate on that data - Class declaration is the programming unit that
ties the data and procedures together - What is an object?
- A specific instance of a class
- Classes are blueprints for actual objects
43.2 Classes, Objects, Methods, and Instance
Variables
53.2 Classes, Objects, Methods, and Instance
Variables
- What is a method?
- A procedure that manipulates data
- Performs a task and returns a result
- Used to hide implementation details from the user
(client) of the class - What is an instance variable?
- the class data
- specifically, a variable that represents an
attribute
63.2 Classes, Objects, Methods, and Instance
Variables
73.2 Classes, Objects, Methods, and Instance
Variables
- What is a message?
- A call to a method of a class
- Tells the class to perform a task
- A client sends a message (method call) to an
object - Example
- currentBalance smith45729.checkBalance()
- Reads as "send a checkBalance message to
smith45729, which returns the result to local
variable currentBalance" - More commonly read as "call checkBalance for
smith45729 and return result to currentBalance"
83.2 Classes, Objects, Methods, and Instance
Variables
- import Target
- // simple example of a storm trooper class
declaration - public class ImperialStormTrooper
- // instance variables
- private boolean isAlive // status
- private Location currentLocation //location
in Deathstar - // method to determine if Storm Trooper is
still alive - public boolean isAlive()
- return isAlive
-
- // method to kill off Storm Trooper
- public void die()
- isAlive false
-
- // method to have Storm Trooper chase a
specific target - public void chaseTarget( Target goodGuy)
93.3 Declaring a Class with a Method and
Instantiating an Object of a Class
- // Fig 3.1 GradeBook.java
- // Class declaration with one method.
- public class GradeBook
-
- // display a welcome message to the GradeBook
user - public void displayMessage()
- System.out.println(" Welcome to the
GradeBook! ") - // end method displayMessage
- // end class GradeBook
103.3 Declaring a Class with a Method and
Instantiating an Object of a Class
- // Fig 3.2 GradeBookTest.java
- // Create a GradeBook object and call its
displayMessage method - 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 main
- // end class GradeBookTest
-
113.3 Declaring a Class with a Method and
Instantiating an Object of a Class
- Deitel uses two classes throughout Chapter 3
- copy these files onto your local machine and
compile - javac .java (or javac GradeBook.java
GradeBookTest.java) - class GradeBook
- simple class to keep track of information for a
single course - in Ch 3, we'll add attributes course name and
instructor name - in later chapters, we'll add grades, class
averages, etc - does NOT contain a main method
- class GradeBookTest
- an application program that contains only a main
method - we'll declare and use a GradeBook object for our
course here - could declare multiple GradeBook objects, one for
each course we want to track
123.3 Declaring a Class with a Method and
Instantiating an Object of a Class
- Some observations about class GradeBook
- Class name and file name are the same (GradeBook)
- Keyword public is an access modifier
- Determines who has visibility or access to the
class - Discussed in more detail in Chapter 8
- For now, all classes are public - accessible by
anyone - Keyword class indicates we are declaring a class
- GradeBook is the name of the class, and each word
is capitalized - Body of the class begins, ends with curly braces
- GradeBook has one method, called displayMessage
133.3 Declaring a Class with a Method and
Instantiating an Object of a Class
- Some observations about class GradeBookTest
- Class name and file name are the same
(GradeBookTest) - This class also uses public access modifier
- GradeBook class has only one method - main
- Main method header is required to look like this
- public static void main ( String args )
- Keyword static is a method or variable modifier
- it allows the method to be called without first
creating an object from the class - method is called a static method or a class
method - for now, only use static keyword with main method
143.3 Declaring a Class with a Method and
Instantiating an Object of a Class
- Some general observations about methods
- All methods in Java are declared within a class
- Like a class, it starts with an access modifier
- For now, all methods use public access modifier
- Like procedures, methods have a return type
- can be built-in type, like int or char
- can be reference type, like String or Date
- can be void, a special keyword that means "no
return type" - Method name starts with lower case letter, then
all subsequent words are capitalized
(displayMessage)
153.3 Declaring a Class with a Method and
Instantiating an Object of a Class
- Back to GradeBookTest class
- Two statements in Fig 3.2
- A lot going on in the first statement
- GradeBook myGradeBook new GradeBook()
- First declare a variable named myGradeBook
- Its type is GradeBook, the class we declared
earlier - Java allows new types to be created via classes
- This is known as extensibility
- Next we initialize myGradeBook
- keyword new creates a new object of the class
type - in this case, we create a new GradeBook object
- the parentheses are required - they call a
constructor (discussed in detail in a little bit) -
163.3 Declaring a Class with a Method and
Instantiating an Object of a Class
- The second statement is a method call
- myGradeBook.displayMessage()
- The format for this call is always the object's
name, followed by a dot separator, followed by
the method name - This calls the displayMessage method using the
myGradeBook object - Cannot call the displayMessage method without
first creating a GradeBook object to use
173.3 Declaring a Class with a Method and
Instantiating an Object of a Class
- UML class diagram
- Graphically represents a class
- Has three components (from top to bottom)
- Class name
- Instance variables
- Methods
- Plus sign () means public, minus sign (-)
means private - (Pound sign () means protected, but
we'll discuss this in Ch 8)
GradeBook
displayMessage()
183.4 Declaring a Method with a Parameter
- Update the displayMessage method in GradeBook to
accept a parameter - // Fig 3.4 GradeBook.java
- // Class declaration with a method that has a
parameter. - public class GradeBook
-
- // display a welcome message to the GradeBook
user - public void displayMessage( String courseName
) -
- System.out.println( "Welcome to the
gradebook for " - courseName )
- // end method displayMessage
- // end class GradeBook
193.4 Declaring a Method with a Parameter
- Update GradeBookTest application to use the new
method - // Fig 3.5 GradeBookTest.java
- // Create a GradeBook object and pass a String to
displayMessage method - import java.util.Scanner // program uses Scanner
- public class GradeBookTest
- // main method begins program execution
- public static void main( String args )
- Scanner input new Scanner ( System.in )
- //create a GradeBook object and assign it
to myGradeBook - GradeBook myGradeBook new GradeBook()
- // prompt for and input course name
- System.out.println(" Please enter the
course name ") - String nameOfCourse input.nextLine()
// read a line of text - System.out.println() // outputs a blank
line - // call myGradeBook's displayMessage
method and pass nameOfCourse - myGradeBook.displayMessage( nameOfCourse
)
203.4 Declaring a Method with a Parameter
- In summary, methods
- Take an argument list, within a set of
parentheses - If no arguments, just an empty set of parentheses
- Examples of method headers
- public void setCourseName( String name )
- public String getCourseName()
- Methods also use curly braces to start, end the
body - Use a return statement in the body to return a
value - return is a keyword
- methods with a void return type do not need a
return statement
213.4 Declaring a Method with a Parameter
- In summary, method calls
- Always have the format variable name, followed
by a dot separator, followed by the method name - Example myGradeBook.displayMessage()
- Must first instantiate an object to call a method
on it - (except for static methods, which we'll cover
later) - Argument types in the method call must match
those in the method header
223.4 Declaring a Method with a Parameter
- Notes on import declarations
- Let you abbreviate a class that you want to use
- Are not required, but make code easier to read
- java.util.Scanner input new java.util.Scanner (
System.in ) - This is the fully qualified class name
- Don't need to import classes compiled in the same
directory - Considered to be part of the default package
- Classes in the java.lang package are implicitly
imported - Brief description of packages
- A way to group related classes together
- Java has a package statement to specify which
package a class is in
233.5 Instance Variables, set and get Methods
- Each class has attributes associated with it
- Instance variables are variable declarations
within a class - Class variables are static variable declarations,
discussed later - Instance and class variables are also known as
fields - Example
- public class GradeBook
- private String courseName // this is an
instance variable - // course name
for this GradeBook - public void displayMessage()
- System.out.println("Welcome to the grade
book for class " - courseName)
- // end method displayMessage
- // end class GradeBook
243.5 Instance Variables, set and get Methods
- All methods of a class can use that classs
fields - For now, all fields use private access modifier
- No one outside of the class's methods can read or
write a private field - Fields can be either built-in or reference types
- I.e., we can use another class as a type
- Example private courseName String
253.5 Instance Variables, set and get Methods
- Each time an object is instantiated, it gets its
own set of instance variables declared in the
class - GradeBook CSC142GradeBook new GradeBook()
- GradeBook CSC143GradeBook new GradeBook()
263.5 Instance Variables, set and get Methods
- Question If fields are private, how are they
accessed? - Answer with public set and get methods
- Set and get methods allow the class to control
its own data - Known as data-hiding
- Set and get methods sometimes perform
computations or error-checking - Naming convention is to precede the method with
either "set" or "get"
273.5 Instance Variables, set and get Methods
- Set methods take parameters and return void type
- Get methods don't, and return a specific
attribute's value
283.6 Primitive Types vs Reference Types
- Eight primitive types in Java
- boolean, byte, char, short, int, long, float,
double - Primitive types are always lower case
- Note Boolean is a class, not a primitive type
- Instance variables initialized to 0 by default
- Except boolean, which is initialized to false
- Local variables are not initialized by default
- One variable, one location in memory
293.6 Primitive Types vs Reference Types
- Everything else is a reference type
- Classes are reference types
- So are arrays (covered in Chapter 7)
- Reference type variables are called references
- References store the location of an object in
memory and not the actual object - Many references can point to one object
- Reference types are initialized to null
- null is a keyword meaning "reference to nothing"
303.6 Primitive Types vs Reference Types
- Example
- GradeBook csc142GradeBook new GradeBook()
- GradeBook currentGradeBook csc142GradeBook
- Need a reference to invoke an object's method
- csc142GradeBook.setCourseName("Intro to Java 1")
- Thus primitive variables cannot invoke methods
- For those familiar with C or C
- A reference is like a pointer, but you can't
manipulate it - Java does not have pointers
313.6 Primitive Types vs Reference Types
- More examples
- int counter
- int countdown 10
- boolean isAlive true
- String name1
- String name2 "Tracey Sconyers"
- String name3 new String( "Tracey Sconyers" )
- Complex Number complex1
- ComplexNumber complex2 new ComplexNumber( 1.0,
2.0 ) - ComplexNumber complex3 new ComplexNumber(
complex2 )
323.7 Initializing Objects with Constructors
- Question If a reference is initialized to null
when its created, how is memory allocated for its
object? - Answer With new keyword, followed by a
constructor - GradeBook csc142GradeBook new GradeBook()
- A constructor is a method that initializes the
instance variables of the object - Can only be called during object creation
- new GradeBook() is the class instance creation
expression -
333.7 Initializing Objects with Constructors
- Constructors
- Always have the same name as the class
- Can be added to any class
- May contain parameters, to initialize instance
variables - Can have multiple constructors in a class
- must have unique parameter list (signature)
- Multiple methods with same name called
overloading - Do not have a return type, not even void
- Do not have return statement
343.7 Initializing Objects with Constructors
- Compiler will provide a default constructor if
programmer doesn't include one - Otherwise, compiler won't create default
constructor - Good programming practice to include constructors
353.7 Initializing Objects with Constructors
- //class to represent complex numbers, such as 2
3i - public class ComplexNumber
- private double myRealPart, myImagPart
- public ComplexNumber()
- myRealPart 0.0
- myImagPart 0.0
-
- public ComplexNumber( double realPart )
- myRealPart realPart
- myImagPart 0.0
-
- public ComplexNumber( double realPart, double
imagPart ) - myRealPart realPart
- myImagPart imagPart
-
- public ComplexNumber( ComplexNumber copy)
- myRealPart copy.getRealPart()
- myImagPart copy.getImagPart()
363.7 Initializing Objects with Constructors
- //class to test our Complex Number class
- public class ComplexNumberTest
- // the number 0
- ComplexNumber zero new ComplexNumber()
- // the real number 42
- ComplexNumber fortyTwo new ComplexNumber(
42.0 ) - // the imaginary number 2i
- ComplexNumber twoI new ComplexNumber(0.0,
2.0 ) - // the complex number 2 3i
- ComplexNumber twoPlusThreeI new
ComplexNumber( 2.0, 3.0 ) - // end class ComplexNumberTest
373.8 Floating-Point Numbers and Type double
- Two primitive floating point types
- float
- represent single-precision floating point numbers
- have 7 significant digits
- 32 bits
- double
- represent double-precision floating point numbers
- have 15 significant digits
- 64 bits
- literals in Java are stored as double values
- double is preferred over float because of greater
precision
38Variable Scope
- The scope of a variable refers to the body of
code in which the variable can be used - A class or instance variable has a class-wide
scope - Local variables have a scope that is local to the
body of code () in which they are declared
39Class Variables and Class Methods
- The static keyword means the variable or method
belongs to the class and an object - Class variables
- Only one copy per class
- Initialized when the class is loaded by the JVM
- Example private static int totalCount 0
- Class methods (static methods)
- Called using class name, not an object
- Example In class Math
- public static double sqrt( double a )
- double root Math.sqrt( 64.0 )
40Constants
- Use both the static and final modifiers
- Are class variables
- Cannot be modified
- Naming convention is all uppercase letters
- Example
- public static final double PI
3.14159265358979323846
41Freeing Memory for Objects
- Objects are created with new keyword, but there
is no corresponding delete or free method - Handled automatically with garbage collection
- Generally objects are marked for collection when
- No longer referenced by any variable
- Go out of scope
- JVM handles garbage collection during slow times
- More details on garbage collection in Chapter 8
42Summary
- Thus class declarations look like
- // import declarations are listed here
- public class SomeClassName
-
- // instance and class variables are usually
listed first - // methods are listed second
- // constructors
- // set methods
- // get methods
- // other methods
- // end class someClassName
- where all of the above is in a text file named
SomeClassName.java
43Summary
- Instance variable declarations look like
- private lttypegt someVariableName
- Class variable declarations look like
- private static lttypegt someVariableName
- Constants look like
- public static final lttypegt SOMECONSTANTNAME
ltvaluegt - where lttypegt is a built-in or reference type
44Summary
- Method declarations look like
- public static void main ( String args )
-
- // local variables and statements to
perform application - // end method main
- public void someMethodName ( ltparameter listgt
) -
- // local variables and statements go here
- // end method someMethodName
- public ltreturn typegt someMethodName(
ltparameter listgt ) -
- // local variables and statements go here
- return someValue
- // end method someMethodName
- where ltreturn typegt is built-in or reference type
- and ltparameter listgt is a comment separated list
of zero or more parameters of the form lttypegt
variableName
45Displaying Text in a Dialog Box
- Windows and dialog boxes
- Many Java applications use these to display
output - JOptionPane provides prepackaged dialog boxes
called message dialogs
46Outline
47Displaying Text in a Dialog Box
- Package javax.swing
- Contains classes to help create graphical user
interfaces (GUIs) - Contains class JOptionPane
- Declares static method showMessageDialog for
displaying a message dialog
48Entering Text in a Dialog Box
- Input dialog
- Allows user to input information
- Created using method showInputDialog from class
JOptionPane
49Outline