Title: JAVA Workshop
1JAVA Workshop
2Object, Classes, Packages
- Ankur Purwar
- purwar_at_iitk.ac.in
3Objects, Classes, and Packages
- Introduction to Classes
- Object Variables and Object References
- Instantiating Objects
- Using Methods in Objects
- Packages and Importing Classes
- Familiarize yourself with API
4Introduction to Classes
- A class defines the attributes and behavior of a
specific type of object - Attributes are variables declared in the class
- Behaviors are methods defined in the class
- Normally, we access an object by calling a method
defined by its class - We may sometimes access an attribute defined by
its class, but this is discouraged
5Introduction to Classes
- A class has a name that we can use as if it were
a data type when declaring a variable - When we declare a variable with the name of a
class as its type, we are creating an object
variable (can contain a reference to an object) - We access an objects methods / attributes using
the object variable name and the . notation, e.g.
- ClassName objectName //object variable
- objectName.methodName() // Note The ( )
- objectName.variableName // Note No ( )
6Example of a Class Definition
- We can draw a diagram of a class to outline its
important features before writing code its
name, attributes, and behaviors
StateMachine
Class Name
List of its Variables
setState (int input) void . . .
List of its Methods
7Example of a Class Definition
- public class StateMachine
- // an attribute or variable
- private int state
- // a behavior or method
- public void setState (int input)
- state input
-
8Example of a Class Definition
- Declaring a StateMachine object variable
- StateMachine myStateMachine
- Accessing a myStateMachine method
- myStateMachine.setState(1)
- Why cant we just do this?
- myStateMachine.state 1
- Notice the word private in the declaration of the
variable state?
9Prototype for a Class Definition
- We use the Java reserved word private to prevent
access to a variable or method from code that is
written outside the class - We use the Java reserved word public to allow
access to a variable or method from code that is
written outside the class - Normally, we declare variables to be private
- Normally, we declare methods to be public
- We will see some valid exceptions later
10Creating Objects, e.g. String class
- String is a commonly used class
- To declare a variable as an object reference, to
a String, we use the class name of the object as
the type name - String title
- This declaration does not create an object
- It only creates a variable that can hold a
reference to a String object.
11Creating Objects
- We use the new operator to create an object
- Creating an object is called instantiation
- An object is an instance of a particular class
- title is assigned a reference to a String object
that contains (encapsulates) the string Java
workshop
title new String (Java Workshop")
This calls the String constructor, which is a
special method that sets up the object
12Invoking Methods
- Once an object has been instantiated, we can use
the dot operator to invoke or call any of the
objects methods - int count title.length()
- A method may return a value which can be used in
an assignment or expression - The value of count will be set to 13
- A method invocation can be thought of as asking
an object to perform a service
13References
- A primitive variable contains the value itself,
but an object variable contains an object
reference - An object reference can be thought of as a
pointer to the location of the object in memory - Rather than dealing with arbitrary address
values, we often depict a reference graphically
38
num1
Java Workshop"
title
14Assignment Revisited
- The act of assignment takes a copy of a value and
stores it in a variable - For primitive types
num2 num1
15Reference Assignment
- For object references, assignment copies the
address
Java Workshop"
title
Before
Anant lab"
title2
title2 title
Java Workshop"
title
After
title2
Garbage See later slide
Anant Lab"
16Aliases
- Two or more references that refer to the same
object are called aliases of each other - That creates an interesting situation one object
can be accessed using more than one reference
variable - Aliases can be useful, but should be managed
carefully - Changing an object via one reference variable
changes it for all of its aliases, because there
is really only one object
17Garbage Collection
- When there are no longer any variables containing
a reference to an object (e.g. Anant Lab on the
earlier slide), the program can no longer access
it - The object is useless and is considered garbage
- Periodically, Java performs automatic garbage
collection and returns an object's memory to the
system for future use - In other languages such as C/C, the programmer
must write explicit code to do the garbage
collection
18Garbage Collection
- Setting object variables value equal to null,
makes the object garbage (unavailable)
Before
Java Workshop"
title
title null
null
title
After
No object
Garbage now
Java Workshop"
19Garbage Collection
- If an object variables value is equal to null,
any reference to an attribute or method of that
object will cause your program to fail.
String title new String(Java
Workshop) System.out.println(title.length())
// prints 13 title null System.out.println(ti
tle.length()) // fails
20The String Class
- Because strings are so common, we don't have to
use the new operator to create a String object - title Java Workshop"
- This special syntax works only for strings
- Each string literal (enclosed in double quotes)
represents a String object
21String Methods
- Once a String object has been created, neither
its value nor its length can be changed - Thus we say that an object of the String class is
immutable - However, several methods of the String class
return new String objects that are modified
versions of the original - See the list of String methods in API
22String Indexes
- It is occasionally helpful to refer to a
particular character within a string - This can be done by specifying the character's
numeric index - The indexes begin at zero in each string
- In the string Java Workshop", the character J'
is at index 0 and the W' is at index 5
23Class Libraries
- A class library is a collection of classes that
we can use when developing programs - The Java standard class library is part of any
Java development environment - Its classes are not part of the Java language per
se, but we rely on them heavily - Various classes we've already used (System,
Scanner, String) are part of the Java standard
class library (Look them up in API!) - Other class libraries can be obtained through
third party vendors, or you can create them
yourself
24Packages
- The classes of the Java standard class library
are organized into packages - Some packages in the standard class library are
25The import Declaration
- When you want to use a class contained in a
package, you can use its fully qualified name - java.util.Scanner scan ...
- Or you can import the package containing the
class and just use the class name Scanner - import java.util.Scanner
- Scanner scan ...
- To import all classes in a particular package,
you can use the wildcard character - import java.util.
26The import Declaration
- All classes of the java.lang package are imported
automatically into all programs - It's as if all programs contain the following
line - import java.lang.
- That's why we didn't have to import the System or
String classes explicitly in earlier programs - The Scanner class, on the other hand, is part of
the java.util package, so that class must be
imported as part of its package
27Formatting, Wrapper Classes
- Ankur Purwar
- purwar_at_iitk.ac.in
28Formatting, Wrapper Classes
- Random and Math Class
- Formatting Output
- Wrapper Classes and Autoboxing
29The Random Class
- The Random class is part of the java.util package
- It provides methods that generate a sequence of
pseudorandom numbers - A Random object performs complicated calculations
based on a seed value to produce a stream of
seemingly random values - See RandomNumbers.java (Ref Lab3)
30The Math Class
- The Math class is part of the java.lang package
- The Math class contains methods that perform
various mathematical functions - We already covered use of the Math class methods
in solving quadratic equations
31Formatting Output
- When performing calculations with float or double
types, we may have more precision in the result
than is valid or than we need - When we solved quadratic equations, the result
- had 16 digits after the decimal point
- That would be too many digits if the data we were
displaying was dollars and cents where we would
want only two digits after the decimal point
32Formatting Output
- The Java standard class library contains classes
that provide formatting capabilities - The NumberFormat class allows you to format
values as currency or percentages - The DecimalFormat class allows you to format
values based on a pattern - Both are part of the java.text package
33Formatting Output
- The NumberFormat class has static methods that
return a formatter object - getCurrencyInstance()
- getPercentInstance()
- Each formatter object has a method called format
that returns a string with the specified
information in the appropriate format
34Number Format
- // Format Locale locale Locale.CANADA
- String string NumberFormat.getPercentInstance(lo
cale).format(123.45) // 12,345
35Formatting Output
- The DecimalFormat class can be used to format a
floating point value in various ways - For example, you can specify that the number
should be truncated to three decimal places - The constructor of the DecimalFormat class takes
a string that represents a pattern for the
formatted number
36- formatter new DecimalFormat(".")
- s formatter.format(-1234.567) // -1234.6
- formatter new DecimalFormat(".")
- s formatter.format(-1234.567) // -1234.567
- formatter new DecimalFormat(".")
- s formatter.format(-1234.567) // -1234.567
formatter new DecimalFormat(".000000") - s formatter.format(-1234.567) // -1234.567000
37Leading Blanks for Numbers
- There is no Java library mechanism to put leading
blanks on digit strings to achieve right hand
alignment of column of numbers - Need to write nested conditional code
- System.out.println( "Number is "
- (n
- (n
- (n
- n))))
38Wrapper Classes
- The java.lang package contains a wrapper class
that corresponds to each primitive type
39Wrapper Classes
- The following declaration creates an Integer
object which is a reference to an object with the
integer value 40 - Integer age new Integer(40)
- An object of a wrapper class is used in
situations where a primitive value will not
suffice - For example, some objects serve as containers of
other objects - Primitive values could not be stored in such
containers, but wrapper objects could be
40Wrapper Classes
- Wrapper classes may contain static methods that
help manage the associated type - For example, the Integer class contains a method
to convert an integer stored in a String to an
int value - num Integer.parseInt(str)
- Wrapper classes often contain useful constants
- For example, the Integer class contains MIN_VALUE
and MAX_VALUE for the smallest and largest int
values
41Autoboxing
- Autoboxing is the automatic conversion of a
primitive value to a corresponding wrapper
object - Integer obj
- int num 42
- obj num
- The assignment creates the appropriate Integer
object wrapping a value of 42 - The reverse conversion (called unboxing) also
occurs automatically as needed
42Topic for next classGraphical User Interfaces
- Ankur Purwar
- purwar_at_iitk.ac.in