CMSC 202
Java Classes and Objects
3rd Lecture
Object Creation Revisited
In earlier demo code, we wrote statements such as
Date3 myDate = new Date3( );
with the comment that we were creating a new
Date3 object. The expression
new Date3( )
is an invocation of a constructor.
A constructor is a special kind of method used to
create objects and initialize the instance
variables.
Aug 6, 2007
2
Constructors
A constructor is “a special kind of method”
because
– It has the same name as the class it constructs
– It has no return type
– If the class implementer does not define any
constructors, the Java compiler automatically creates
a constructor that has no parameters
Like other methods, constructors may be
overloaded. It’s good programming practice to
always implement a constructor with no
parameters.
Aug 6, 2007
3
The Finished Date Class
public class Date
{
private String month;
private int day;
private int year;
// 1 - 31
//4 digits
// no-argument constructor
// implementer chooses the default month, day, year
public Date( )
{
month = “January”;
day = 1;
year = 2007;
}
// alternative constructor
public Date( int month, int day, int year )
{
setDate( month, day, year);
}
(continued)
Aug 6, 2007
4
Date Class
// another alternative constructor
public Date( int newYear )
{
setDate (1, 1, newYear );
}
// a constructor which makes a copy of an existing Date object
// discussed in more detail later
public Date( Date otherDate )
{
if (otherDate != null )
{
month = otherDate.month;
day = otherDate.day;
year = otherDate.year;
} else {
// do nothing?
}
}
// remaining Date methods such as setDate, accessors, mutators
// equals, toString, and stringMonth
} // end of Date class
Aug 6, 2007
5
Using Date Constructors
public class DateDemo
{
public static void main( String[ ] args)
{
Date birthday = new Date( 1, 23, 1982 );
birthday.print( );
// January 23, 1982
Date newYears1990 = new Date( 1990 );
newYears1990.print( );
// January 1, 1990
Date holiday = new Date( birthday );
holiday.print( );
// January 23, 1982
Date defaultDate = new Date( );
defaultDate.print( );
// January 1, 1000
}
}
Aug 6, 2007
6
Static Methods
Up to now, all class methods required a calling
object in order to be invoked.
Date birthday = new Date( 1, 23, 1982);
birthday.print( );
But there are many methods which are usable
without a calling object such as simple math
functions which compute the maximum and
minimum of two integers.
Such methods are called static methods.
Although they need no calling object, static
methods (like everything else in Java) must
belong to a class.
Aug 6, 2007
7
monthString again
Recall that our Date class had a helper method that translated an integer
month to a string. Note that this method does not call any other methods of
the Date class, nor does it use any instance variables (month, day, year)
from the Date class.
If we choose, we can make this method available to users of the Date class
without requiring them to create a Date object
// change month number to string
public static String monthString( int monthNumber ) {
switch ( monthNumber ) {
case 1: return "January";
case 2: return "February";
case 3: return "March";
case 4: return "April";
case 5: return "May";
case 6: return "June";
case 7: return "July";
case 8: return "August";
case 9: return "September";
case 10: return "October";
case 11: return "November";
case 12: return "December";
default: return “????”;
}
}
Aug 6, 2007
8
monthString demo
Code outside of the Date class can now use monthString
without creating a Date object. We prefix the method
name with the name of the class instead of an object.
Class MonthStringDemo
{
public static void main( String [ ] args)
{
String month = Date.monthString( 6 );
System.out.println( month );
}
}
Aug 6, 2007
9
Rules for Static Methods
Since static methods have no calling object,
they have no this. Therefore static
methods cannot
– Refer to any instance variables of the class
– Invoke any method that has an implicit or
explicit this for a calling object
Static methods may, however, invoke other
static methods or refer to static variables
Aug 6, 2007
10
Static Variables
• A static variable is a variable that belongs to the class as
a whole, and not just to one object
– There is only one copy of a static variable per class, unlike
instance variables where each object has its own copy
• All objects of the class can read and change a static
variable
• Although a static method cannot access an instance
variable, a static method can access a static variable
• A static variable is declared like an instance variable,
with the addition of the modifier static
private static int myStaticVariable;
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
11
Static Variables
• A static variable should always be defined private,
unless it is also a defined constant
– The value of a static defined constant cannot be altered,
therefore it is safe to make it public. Making it public
allows other code to use it.
– In addition to static, the declaration for a static defined
constant must include the modifier final, which indicates
that its value cannot be changed
public static final int BIRTH_YEAR = 1954;
• When referring to such a defined constant outside
its class, use the name of its class in place of a
calling object
int year = MyClass.BIRTH_YEAR;
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
12
Static Variables
• Static variables can be declared and initialized at the
same time
private static int myStaticVariable = 0;
• If not explicitly initialized, a static variable will be
automatically initialized to a default value
– boolean static variables are initialized to false
– Other primitive types static variables are initialized to the zero of
their type
– Class type static variables are initialized to null
• It is always preferable to explicitly initialize static
variables rather than rely on the default initialization
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
13
The Math Class
• The Math class provides a number of standard
mathematical methods
– It is found in the java.lang package, so it does not
require an import statement
– All of its methods and data are static, therefore they
are invoked with the class name Math instead of a
calling object
– The Math class has two predefined constants,
E (e, the base of the natural logarithm system)
PI (, 3.1415 . . .)
area = Math.PI * radius * radius;
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
14
Some Methods in the Class Math
(Part 1 of 5)
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
15
Some Methods in the Class Math
(Part 2 of 5)
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
16
Some Methods in the Class Math
(Part 3 of 5)
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
17
Some Methods in the Class Math
(Part 4 of 5)
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
18
Some Methods in the Class Math
(Part 5 of 5)
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
19
Static Review
• Given the skeleton class definition below
public class C
{
public int a = 0;
public static int b = 1;
public void f ( ) { …}
public static void g ( ) {…}
}
•
•
•
•
Can body of f( ) refer to a?
Can body of f( ) refer to b?
Can body of g( ) refer to a?
Can body of g( ) refer to b?
• What are the rules?
Aug 6, 2007
20
Wrapper Classes
• Wrapper classes provide a class type
corresponding to each of the primitive types
– This makes it possible to have class types that
behave somewhat like primitive types
– The wrapper classes for the primitive types
byte, short, long, float, double, and char
are (in order)
Byte, Short, Long, Float, Double, and Character
• Wrapper classes also contain a number of useful
predefined constants and static methods
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
21
Wrapper Classes
• Boxing: the process of going from a value of a
primitive type to an object of its wrapper class
– To convert a primitive value to an "equivalent" class
type value, create an object of the corresponding
wrapper class using the primitive value as an
argument
– The new object will contain an instance variable that
stores a copy of the primitive value
– Unlike most other classes, a wrapper class does not
have a no-argument constructor
Integer integerObject = new Integer(42);
– The value inside a Wrapper class is immutable (it
can’t be changed)
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
22
Wrapper Classes
• Unboxing: the process of going from an
object of a wrapper class to the
corresponding value of a primitive type
– The methods for converting an object from the
wrapper classes Byte, Short, Integer, Long,
Float, Double, and Character to their
corresponding primitive type are (in order)
byteValue, shortValue, intValue,
longValue, floatValue, doubleValue, and
charValue
– None of these methods take an argument
int i = integerObject.intValue();
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
23
Automatic Boxing and Unboxing
• Starting with version 5.0, Java can automatically do
boxing and unboxing
• Instead of creating a wrapper class object using the new
operation (as shown before), it can be done as an
automatic type cast:
Integer integerObject = 42;
• Instead of having to invoke the appropriate method (such
as intValue, doubleValue, charValue, etc.) in
order to convert from an object of a wrapper class to a
value of its associated primitive type, the primitive value
can be recovered automatically
int i = integerObject;
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
24
Constants and Static Methods
in Wrapper Classes
• Wrapper classes include useful constants that
provide the largest and smallest values for any
of the primitive number types
– For example, Integer.MAX_VALUE,
Integer.MIN_VALUE, Double.MAX_VALUE,
Double.MIN_VALUE, etc.
• The Boolean class has names for two
constants of type Boolean
– Boolean.TRUE and Boolean.FALSE are the
Boolean objects that correspond to the values true
and false of the primitive type boolean
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
25
Constants and Static Methods
in Wrapper Classes
• Wrapper classes have static methods that convert a
correctly formed string representation of a number
to the number of a given type
– The methods Integer.parseInt, Long.parseLong,
Float.parseFloat, and Double.parseDouble do
this for the primitive types (in order) int, long, float,
and double
• Wrapper classes also have static methods that
convert from a numeric value to a string
representation of the value
– For example, the expression
Double.toString(123.99);
returns the string value "123.99"
• The Character class contains a number of static
methods that are useful for string processing
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
26
Methods in the Class Character (1 of 3)
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
27
Methods in the Class Character (2 of 3)
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
28
Methods in the Class Character ( 3 of 3)
Aug 6, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
29