Using and Making Classes

eyelashesnectarineSoftware and s/w Development

Nov 3, 2013 (4 years and 6 days ago)

60 views

Using and Making Classes

BCIS 3680 Enterprise Programming

Overview

2


Using Classes


Class and object


Using premade classes for input and output


Display output: System,
JOptionPane

classes


Format output: Decimal Format,
NumberFormat

classes


Handling Input: Wrapper classes, e.g., Integer, Double


Processing: Math class


Building Your Own Classes


Members of a class


Variables (instance and static)


Methods (instance and static)


Storing and accessing values in an object


Constructor methods


Getter and setter methods

Class

3


A class defines a number of properties (variables) and
actions/behaviors (methods).


An object created from this class will have those variables and
methods.


Variables are used to store data.


Methods are used to specify action.


Object vs. Class

4


Object reference


Identifier (name)
of the
object


H
olds the address of the object


A class is a template for making objects.


An object is an
instance

of a class.


The process of creating an object out of a template (class) is
called
instantiation
, “creating an instance of the class”, etc.


Remember the naming convention:


The name of a
class

starts with an
uppercase

letter.


The name of a
variable

starts with a
lowercase

letter.

Creating Objects

5


Two things required to create an object:


Declaring an object reference for the new object,

ClassName

objRef
;

e.g.,
Student
cobStudent
;


Using the
new

keyword to actually create the object,

objRef

= new
ClassName
([arguments]);
e.g.,

cobStudent

= new Student("ITDS", "Undergrad");



The two steps may be combined into one:

ClassName

objRef

= new
ClassName
([arguments]);

Student
cobaStudent

= new Student("ITDS",
"Undergrad"); // One step

Using Objects

6


To use an object’s variables and methods, you use the “.”
operator (dot notation).

objectName.variableName

cobStudent.dept

= "Marketing";

objectName.methodName
([arguments]);

cobStudent.regClass
("BCIS3680");

Organization of Classes

7


Related classes are organized into packages.


Java SE comes with a number of commonly used packages.


To use Class A in Class B, you need to have an
import

statement for Class A at the beginning of Class B.


The only exception is the classes in the
java.lang

package,
which can be used by all other classes without an
import
java.lang
;

statement.


Two ways to write the
import

statement:


Specifically import the name of the particular class you want to use,
e.g.,
import
java.util.Scanner
;
.


Import the entire package the class belongs to, e.g.,
import
java.util
.*;
.


All other classes in that package are accessible now.

Packages of “Premade” Classes

8


Classes are grouped in packages according to functionality by using
the
package

keyword.


The following packages ship with the Java language:













Package

Categories of Classes

java.lang

Basic functionality common to many programs, such as
the
String

class and
Math

class

java.awt

Graphics classes for drawing and using colors

javax.swing

User
-
interface components

java.text

Classes for formatting numeric output

java.util

The
Scanner

class, the
Random
class and other
miscellaneous classes

java.io

Classes for reading from and writing to files

The
System

Class

9


The
System

class is in the

java.lang

package, so
it does not need to be imported
.


Two useful static

constants (variables with constant value)
of the
System

class:


in

represents
the standard input device (the keyboard by default
).


out

represents
the standard output device (the Java console by default
).


Examples:


Scanner scan = new
Scanner(
System.in
);


System.out.println
("Hello");

Using
System.out

Example:


System.out.print
("The answer is ");


System.out.println
(3);



The output is:


The answer is 3


Return type

Signature

void

print(
anyDataType

argument )

prints
argument

to the standard output device

void


println
(
anyDataType

argument )

prints
argument

to the standard output device followed by a
newline character

Using Dialog Boxes

11


The
JOptionPane

class is in the
javax.swing

package.


You must import it.


Static methods are provided for input and output dialog boxes.


For input dialog boxes, return value is a
String
, so numeric input
needs to be converted (using methods such as
parseInt
()

or
parseDouble
()
).

JOptionPane

static Methods

12

Return value

Signature

String

showInputDialog
( Component
parent, Object prompt,
String
title,
int

messageType

)

pops up an input dialog box, where prompt
asks the user for input.


void

showMessageDialog
( Component
parent, Object message,
String
title,
int

messsageType

)

pops up an output dialog box with
message

displayed.


Message Dialog Box

13


Displays a message and then waits until the user press OK:
showMessageDialog
(Component parent, Object
message, String title,
int

messageType
)


parent


use null for projects


mesage



the message you want to display. A string is fine as it is an object.


title


the text you want to appear on the title bar.


messageType



indicates the nature of the message box. It is of the
int

type
but you don’t have to enter an integer. Instead, you may enter one of the
following easy
-
to
-
read words and Java will translate it into an integer for you.


JOptionPane.INFORMATION_MESSAGE
: Standard info icon is used.


JOptionPane.PLAIN_MESSAGE
: No icon is displayed.


JOptionPane.QUESTION_MESSAGE
: Question mark icon is displayed.


JOptionPane.WARNING_MESSAGE
: Warning icon is displayed.

Input Dialog box

14


Displays a displays a text field into which the user can enter a string.


showInputDialog
(Component parent, Object
prompt, String title,
int

messsageType
)


parent


use null for projects


prompt


the prompt you want to display. A string is fine as it’s an object.


title


the text you want to appear on the title bar.


messageType



indicates the nature of the message box. The options are:


JOptionPane.ERROR_MESSAGE


JOptionPane.INFORMATION_MESSAGE


JOptionPane.PLAIN_MESSAGE


JOptionPane.QUESTION_MESSAGE


JOptionPane.WARNING_MESSAGE

Formatting Numeric Output

15


The
DecimalFormat

and
NumberFormat

classes allow you
to specify the display format of numbers
-

number of digits, number of
places after the decimal, formatting elements such as dollar signs and
percent signs, etc.


Both classes are in the
java.text

package.


Importing is needed.


Usage pattern:


Create a formatting object (either a
DecimalFormat

or a
NumberFormat

object).


Call the
format

method of the formatting object and pass the number to
be formatted as the argument.


A formatting object may be used to format multiple numbers.


If numbers are to be formatted in different ways, then multiple formatting
objects are needed.

DecimalFormat

Class

16




Pattern characters:


0 required digit


# optional digit, suppress if 0


. decimal point


, comma separator


% multiply by 100 and display a percent sign

DecimalFormat

Constructor

DecimalFormat
( String pattern )

instantiates a

DecimalFormat

object with the format
specified by
pattern

The
format( )
Method

17






Return type

Signature

String

format( double number )

returns a formatted
String

representation of
number

The Wrapper Classes

18


There are occasions when you want to work with a number as
an object.


Numbers are primitive types. They are not objects.


Wrapper classes resolve the problem because they are objects so can
be handled as such.


In the “core” of each wrapper object is a numeric value.

Wrapper Classes

19


Remember the naming convention:


Primitive types start with a lowercase letter; Class names start with an
uppercase letter.

Primitive Data Type

Wrapper Class

double

Double

float

Float

long

Long

int

Integer

short

Short

byte

Byte

char

Character

boolean

Boolean

Using Wrapper Classes

20


A handy use of wrapper class is a static method for converting
textual input into numbers.


Usually, when a program obtains input from users, the input is
read as strings. Even when the user enters a number, it’s still a
string (of characters that stand for numbers).


Despite looking numeric ostensibly, such strings cannot be used
in mathematic operations. They must be converted into primitive
types first.


To perform the conversion, call the respective
parseX
()

method of the wrapper class.


To convert a string into an integer, call
parseInt
()
.


To convert a string into a double, call
parseDouble
()
.

Integer

Static Methods

21

Return value

Signature

int

parseInt
( String s )

returns the
String s

as an
int


Integer

valueOf
( String s )

returns the
String s
as an
Integer
object

Double

Static Methods

22

Return value

Signature

double

parseDouble
( String s )

returns the
String s

as a
double

Double

valueOf
( String s )

returns the
String s
as a
Double
object

Reading Numeric Input

23


The
showInputDialog
()

method returns a
string
.


To convert the s
tring
to a numeric type, use the wrapper
class methods
.


Example:

String input =


JOptionPane.showInputDialog
(null,

"Please
enter your age in
years.", "Get Input",

JOptionPane.QUESTION_MESSAGE
);

int

age =
Integer.parseInt
(input);


Math

Class

24


The
Math

class provides
static

constants and
static

methods
for performing common calculations.


The
Math

class is in the
java.lang

package, so it does not
need to be imported
.


Methods in the
Math

class are static.

Methods of the
Math

Class

25

Return type

Signature

dataTypeOfArg

abs(
dataType

arg

)


returns the absolute value of the argument
arg
,
which can be a
double, float,
int

or
long
.

double

log( double a )


returns the natural logarithm (in base e) of its
argument.

double

sqrt
( double a )


returns the positive square root of a


double

pow
( double base, double exp )


returns the value of
base

raised to the power
exp


The
round()

Method

26


Rounding
rules:


Any factional part < .5 is rounded down


Any fractional part .5 and above is rounded
up

Return type

Signature

long

round( double a )


returns the closest integer to its argument
a

The
min()

and
max()
Methods

27








Find
smallest of three numbers:


int

smaller = Math.min( num1, num2
);


int

smallest = Math.min( smaller,
num3 );


Return type

Signature

dataTypeOfArgs

min(
dataType

a,
dataType

b )

returns the smaller of the two arguments. The
arguments can be

doubles, floats,
ints
,
or
longs.

dataTypeOfArgs

max(
dataType

a,
dataType

b )

returns the larger of the two arguments. The
arguments can be

doubles, floats,
ints
,
or
longs.

Instance Variable

28


Instance variables

are used to store data specific to a particular
object.


An instance variable doesn’t exist (no memory location is assigned to
it) until an object of that class is created.


Different objects of the same class may have different values stored
in the same instance variable.


Example:


The
Student

class has an instance variable called
untId
.


alice

and
bob

are two instances of the
Student

class.


In the
alice

object, the
untId

variable contains the value
10101111
.


In the
bob

object, the
untId

variable contains the value
10102222
.

Static Variable

29


A class may also contain
static variables
.


Once a static variable is defined in the class, it comes into being
immediately. No instantiation is needed.


Static variables can be accessed from outside of the class by
following the
ClassName.staticVarName

syntax.


It can be used to store class
-
related data that is relevant to all
instances of the class.


Example:


The
Student

class has a
studentCount

static variable.


The number of all
Student

objects ever created can be stored in
the
studentCount

variable.

Instance Method

30


Instance methods
are used to define actions that an object of the class is
capable of performing.


An instance method cannot be called until an object of that class is created.


Unlike with instance variables, all objects of the same class will act the same
way when an instance method is called. However, even if the action is the
same, different objects often work on different data (stored in their respective
instance variables).


Example:


The
Student

class has an instance method called
printStudentId
()
.


alice

and
bob

are two instances of the
Student

class.


When called on the
alice

object, the
printStudentId
()
method
displays the value
10101111
.


When called on the
bob

object, the
printStudentId
()
method displays
the value
10102222
.


Static Method

31


A class may also contain
static methods
.


Once a static method is defined in the class, it comes into being
immediately. No instantiation is needed.


Static methods can be accessed from outside of the class by
following the
ClassName.staticMethod
()

syntax.


It can be used to perform action that is relevant to all instances of the
class.


Example:


The
Student

class has an
addToCount
()
static method and a
getStudentCount
()
static method.


The
addToCount
()
method increments the student count whenever a
new student object is instantiated.


The
getStudentCount
()
method displays the current count of student
objects.

Members of A Class

32

The OOP “PIE”

33

Encapsulation


A fundamental concept in OOP.


The values of instance variables inside a class shouldn’t be
changed arbitrarily by other classes.


They should be declared as “private”.


Manipulation of their values are done only by special
-
purpose
methods inside the class.


These methods are public and “exposed”.


Setting values is possible only through calling these methods.


If program logic requires that these values to be changed, regardless
of where the program execution is done, these special
-
purpose
methods must be called.

34

Encapsulation


For example, suppose the
main

method is inside the
Driver

class and it needs to set the value of
studentID

of a
Student

object called
alice
,


It shouldn’t do:
alice.studentID

= "12345";


Instead, the setter method of that property should be run:
alice.setStudentID
("12345");


Whether a field or method is accessible (visible) to other classes
is controlled by access modifiers.


public

(UML sign + )


All other classes can access the member.


private

(UML sign
-

)


Other classes must access the member
through special methods defined in this class.

35

UML Representation of a Class


+ public
-

private

36

Access Modifiers

Visibility

Public

Protected

<None>

Private

Within

the same class

Yes

Yes

Yes

Yes

From any class in the same
package

Yes

Yes

Yes

No

From a subclass in the same
package

Yes

Yes

Yes

No

From a subclass outside the
package

Yes

Yes*

No

No

From any non
-
subclass class
outside the package

Yes

No

No

No


* Through inheritance

37

Storing Values to Instance Variables


Constructor Methods


A
constructor

is a special method that is run when an object is
created. It is typically used to set initial (default) values for instance
variables.


A class may have more than one constructor, i.e.,
constructors often
are
overloaded
.


Setter (
mutator
) Methods


A
setter method

is a void method that performs an action (set the
value of an instance variable).


It takes a parameter


the value to be stored in the variable.


It does not return a value.

38

Accessing Values of Instance Variables

39


Getter (
Accessor
) Methods


A
setter method

is a value
-
returning method that returns a value (the
value of an instance variable).


It does not have parameters.

Constructor


When an object is instantiated, the instantiation process runs the
class’ constructor method.


If the business rules of your application require other initial
values for (some of all) variables in your class, then you need to
write a constructor and assign initial values to those that need
them.


A constructor may also perform some initial actions in addition to
or instead of setting initial values for variables.


Besides initializing instance variables, a constructor may also
work with static variables/methods of the class.


A constructor must use the same name and capitalization as the
name of the class.

40

Default Initial Values


If you haven’t defined a constructor for the class, Java will create
a default constructor for you



Data Type

Default Value

byte, short, int, long

0

float, double

0.0

char

space

boolean

false

Any object reference (e.g.,
String
)

null

41

Overloaded Constructor


Often, even though objects are instantiated from the same class,
you want their variables to be initialized differently or different
sets of variables to be initialized.


To achieve that, you write a few different constructors
accordingly.


Constructors often are overloaded.

42

Setter Method

43


The program logic may need to change the value of an instance
variable after it is initialized by the constructor. To do that, the
setter method of that variable needs to be called.


The design pattern of a setter:


Access modifier:
public


Return value:
void


Naming:
setVarName


Parameter list: one and only one parameter


(
dataType

paramName
)


Method body: although more complicated assignment may be needed
sometimes, typically the method contains only one assignment
statement that assigns the parameter value to the variable


varName

=
paramName
;

Getter Method

44


A getter method retrieves the value of an instance variable on
behalf of methods in external classes.


The design pattern of a getter:


Access modifier:
public


Return value:
<
dataTypeOfVar
>


Naming:
getVarName


Parameter list:
()


Method body: although more complicated actions may be needed
sometimes, typically the method contains only one statement that
returns the value of the variable


return
varName
;

Access Method Examples


Example:

// Declare the property

private double
unitPrice
;



// The setter method

public void
setUnitPrice

(double price) {


unitPrice

= price;

}

// The getter method

public double
getUnitPrice

{


return
unitPrice
;

}


45

The
this

Keyword


If inside a constructor or setter method, the parameter name is the
same as the name of the instance variable that will be assigned the
parameter’s value, there should be a way to differentiate the
“namesakes.”


The
this

keyword is used to refer to the
object

itself.


Variable name preceded by
this

and a dot refers to the instance
variable itself.


Variable name standing by itself refers to the parameter.

public void
setUnitPrice

(double
unitPrice
)

{


this.unitPrice

=
unitPrice
;

}

46