Topics
static variables and methods (revisit) enum types Java pre-defined classes String
static Variables
You want to create a class member that will be used independently of any object of the class Also called class variables One copy of a static variable is created per class static variables are not associated with an object static constants are often declared as public To define a static variable, include the keyword static in its definition: Syntax:
accessSpecifier static dataType variableName;
Example:
public static int countAutos = 0;
static Methods
Also called class methods Often defined to access and change static variables static methods cannot access instance variables: static methods are associated with the class, not with any object. static methods can be called before any object is instantiated, so it is possible that there will be no instance variables to access.
Rules for static and Non-static Methods
static Method Access instance variables? Access static class variables? Call static class methods? no yes yes Non-static Method yes yes yes
Call non-static instance methods? Use the object reference this?
no
no
yes
yes
enum Types
Special class definition designed to increase the readability of code Allows you to define a set of objects that apply names to ordered sets Examples of ordered sets: Days of the week Months of the year Playing cards
enum
Built into [Link] (no import statement needed) Syntax:
enum EnumName { obj1, obj2, objn };
Example
enum Days { Sun, Mon, Tue, Wed, Thurs, Fri, Sat };
A constant object is instantiated for each name in the list. Thus, each name is a reference to an object of type Days
Using an enum Object
Referring to an enum object reference Syntax:
[Link]
Example:
[Link]
Declaring an object reference of an enum type Syntax:
EnumType referenceName
Example:
Days d; // d is null initially d = [Link];
Useful enum Methods
Return value
int
Method name and argument list
compareTo( Enum eObj )
compares two enum objects and returns a negative number if this object is less than the argument, a positive number if this object is greater than the argument, and 0 if the two objects are the same.
int ordinal( )
returns the numeric value of the enum object. By default, the value of the first object in the list is 0, the value of the second object is 1, and so on.
More Useful enum Methods
Return value
boolean
Method name and argument list
equals( Enum eObj )
returns true if this object is equal to the argument eObj; returns false otherwise.
String Enum toString( )
returns the name of the enum constant
valueOf( String enumName )
static method that returns the enum object whose name is the same as the String argument enumName.
Using enum Objects with switch
Using enum objects for case constants makes the code more readable. Use the enum object reference without the enum type Example:
case Fri: