Download Java API and Object-Oriented Programming Concepts and more Study notes Computer Science in PDF only on Docsity!
Chapter 3
Introduction to
Object-Oriented Programming:
Using Classes
OO Programming
CS201 Home Page
Find Weighted Average
Print Weighted Average
Module Structure Chart
Main
Print Data
Print Heading
Get Data
Prepare File for Reading
CS201 Home Page
Two Design Strategies
FUNCTION
FUNCTION
FUNCTION
OBJECT
.. .. .... ....^ OBJECT
.... .... ....
OBJECT
.... .... ....
FUNCTIONAL OBJECT-ORIENTED
DECOMPOSITION DESIGN
CS201 Home Page
Topics
- Class Basics and Benefits
- Creating Objects Using Constructors
- Calling Methods
- Using Object References
- Calling Static Methods and Using Static
Class Variables
- Using Predefined Java Classes
CS201 Home Page
Object-Oriented Programming
- Classes combine data and the methods
(code) to manipulate the data
- Classes are a template used to create
specific objects
- All Java programs consist of at least one
class.
- Two types of classes
- Application/Applet classes
- Service classes
CS201 Home Page
Example
- Student class
- Data: name, year, and grade point average
- Methods: store/get the value of each piece of
data, promote to next year, etc.
- Student Object: student
- Data: Maria Gonzales, Sophomore, 3.
CS201 Home Page
Some Terminology
- Object reference : identifier of the object
- Instantiating an object : creating an object
of a class
- Instance of the class : the object
- Methods: the code to manipulate the object
data
- Calling a method : invoking a service for an
object.
CS201 Home Page
Class Data
- Instance variables : variables defined in the
class and given values in the object
- Fields : instance variables and static
variables (we'll define static later)
- Members of a class: the class's fields and
methods
- Fields can be:
- any primitive data type ( int , double , etc.)
- objects
CS201 Home Page
Encapsulation
- Instance variables are usually declared to be
private , which means users of the class
must reference the data of an object by
calling methods of the class.
- Thus the methods provide a protective shell
around the data. We call this
encapsulation.
- Benefit: the class methods can ensure that
the object data is always valid.
CS201 Home Page
Naming Conventions
- Class names: start with a capital letter
- Object references: start with a lowercase
letter
- In both cases, internal words start with a
capital letter
objects: student1, student
CS201 Home Page
Reusability
- Reuse : class code is already written and
tested, so you build a new application faster
and it is more reliable
Example: A Date class could be used in a
calendar program, appointment-scheduling
program, online shopping program, etc.
CS201 Home Page
Example 3.1 Constructors.java
public class Constructors
{
public static void main( String [] args )
{
Date independenceDay;
independenceDay = new Date( 7, 4, 1776 );
Date graduationDate = new Date( 5, 15, 2008 );
Date defaultDate = new Date( );
}
}
Figure Next Slide CS201 Home Page
Objects After Instantiation
CS201 Home Page
Calling a Method
CS201 Home Page
Method Classifications
- Accessor methods
- get…
- gives values of object data
- Mutator methods
- set…
- change values of object data
CS201 Home Page
Date Class Methods
Return value Method name and argument list
getMonth( )
returns the value of month
int
getDay( )
returns the value of day
int
getYear( )
returns the value of year
int
setMonth( int mm )
sets the value of month to mm
void
setDay( int dd )
sets the value of day to dd
void
setYear( int yy )
sets the value of year to yy
void
CS201 Home Page
The Argument List in an API
dataType variableName
- Specify
- Order of arguments
- Data type of each argument
- Arguments can be:
- Any expression that evaluates to the specified data type
CS201 Home Page
- When calling a method, include only
expressions in your argument list. Including
data types in your argument list will cause a
compiler error.
- If the method takes no arguments,
remember to include the empty parentheses
after the method's name. The parentheses
are required even if there are no arguments.
CS201 Home Page
Void Methods
- Void method Does not return a value
System.out.print(“Hello”);
System.out.println(“Good bye”);
name.setName(“CS”, “201”);
object method arguments
CS201 Home Page
Value-Returning Methods
- Value-returning method Returns a value
to the calling program
String first; String last;
Name name;
System.out.print(“Enter first name: “);
first = inData.readLine();
System.out.print(“Enter last name: “);
last = inData.readLine();
name.setName(first, last);
CS201 Home Page
Value-returning example
public String firstLastFormat()
{
return first + “ “ + last;
}
System.out.print(name.firstLastFormat());
object method object method
Argument to print method is string returned from
firstLastFormat method
CS201 Home Page
Method Return Values
- Can be a primitive data type, class type, or
void
- A value-returning method
- Return value is not void
- The method call is used in an expression. When the expression is evaluated, the return value of the method replaces the method call.
- Methods with a void return type
- Have no value
- Method call is complete statement (ends with ;)
CS201 Home Page
Dot Notation
- Use when calling method to specify which
object's data to use in the method
objectReference.methodName( arg1, arg2, … )
Note: no data types in method call; values only!
Example Next Slide
CS201 Home Page
Example 3.5 NullReference2.java
public class NullReference2 {
public static void main( String[] args ) {
Date independenceDay = new Date( 7, 4, 1776 );
System.out.println( "The month of independenceDay is “ + independenceDay.getMonth( ) );
independenceDay = null; // attempt to use object reference
System.out.println( "The month of independenceDay
is “ + independenceDay.getMonth( ) ); }
}
CS201 Home Page
Date.java Class
import java.awt.Graphics; public class Date { private int month; private int day; private int year;
public Date( ) { setDate( 1, 1, 2000 ); } public Date( int mm, int dd, int yyyy ) { setDate( mm, dd, yyyy ); } /* accessor methods / int getMonth( ) { return month; } int getDay( ) { return day; } int getYear( ) { return year; } /* mutator method */ public void setMonth( int mm ) { month = ( mm >= 1 && mm <= 12? mm : 1 ); }
CS201 Home Page
Date.java Class
public void setDay( int dd ) { int [] validDays = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; day = ( dd >= 1 && dd <= validDays[month]? dd : 1 ); } public void setYear( int yyyy ) { year = yyyy; } public void setDate( int mm, int dd, int yyyy ) { setMonth( mm ); setDay( dd ); setYear(yyyy); } public String toString( ) { return month + "/" + day + "/" + year; } public boolean equals( Date d ) { if ( month == d.month && day == d.day && year == d.year ) return true; else return false; }
} CS201 Home Page
static Methods
- Also called class methods
- Can be called without instantiating an
object
- Might provide some quick, one-time
functionality, for example, popping up a
dialog box
- In method API, keyword static precedes
return type
static dataType methodName (arg1,ard2,…);
CS201 Home Page
Calling static Methods
- Use dot syntax with class name instead of
object reference
ClassName.methodName( args )
int absValue = Math. abs ( -9 );
- Uses of class methods
- Provide access to class variables without using an object
CS201 Home Page
static Class Variables
ClassName.staticVariable
Color.BLUE
BLUE is a static constant of the Color class.
CS201 Home Page
Static Class Variables and Static Mthods
class Counter {
private int value;
private static int numCounters = 0;
public Counter() {
value = 0;
numCounters++;
public static int getNumCounters() {
return numCounters; }
System.out.println("Number of counters: "
+ Counter.getNumCounters()); CS201 Home Page
- Class (static) vs. instance variables
- Instance variable: each instance has its own copy
- Class variable: the class has one copy for all instances
- Can use instance variables
- Can use class variables
- In instance methods
- In class methods
CS201 Home Page
Using Java Predefined Classes
- Java Packages
- The String Class
- Using System.out
- Formatting Output
- The Math Class
- The Wrapper Classes
- Dialog Boxes
- Console Input Using the Scanner Class
CS201 Home Page
Java Predefined Classes
- Included in the Java SDK are more than
2,000 classes that can be used to add
functionality to our programs
- APIs for Java classes are published on Sun
Microsystems Web site:
http://www.java.sun.com
CS201 Home Page
Java Packages
- Classes are grouped in packages according
to functionality
java.util The Scanner class and other miscellaneous classes
java.text Classes for formatting numeric output
javax.swing User-interface components
java.awt Graphics classes for drawing and using colors
Basic functionality common to many programs, such as the String class and Math class
java.lang
Package Categories of Classes
CS201 Home Page
Using a Class From a Package
- Classes in java.lang are automatically
available to use
- Classes in other packages need to be
"imported" using this syntax:
import package.ClassName;
or
import package.*;
import java.text.DecimalFormat;
or
import java.text.*;
CS201 Home Page
- Specifying a negative start index or a start
index past the last character of the String
will generate a
StringIndexOutOfBoundsException.
- Specifying a negative end index or an end
index greater than the length of the String
will also generate a
StringIndexOutOfBoundsException
CS201 Home Page
System.out
- System is a class in java.lang package
- out is a a static constant field, which is an object of class PrintStream.
- PrintStream is a class in java.io package
- Since out is static we can refer to it using the class name
System.out
- PrintStream Class has 2 methods for printing, print and println that accept any argument type and print to the standard java console.
CS201 Home Page
Using System.out
- Example: System.out.print( "The answer is " ); System.out.println( 3 );
output is:
The answer is 3
println ( anyDataType argument ) prints argument to the standard output device (Java console) followed by a newline character
void
print ( anyDataType argument ) prints argument to the standard output device (by default, the Java console)
void
Return Method name and argument list
type
CS201 Home Page
The toString Method
- All classes have a toString method which
converts an object to string for printing
- See Example 3.7 PrintDemo.java
toString ( ) converts the object data to a String for printing
String
Return Method name and argument list type
CS201 Home Page
Formatting Numeric Output
- NumberFormat Class and the DecimalFormat
Class allow you to specify the number of
digits to print and add dollar signs and percent
signs to your output
- Both classes are in the java.text package
CS201 Home Page
The NumberFormat Class
- See Example 3.8 DemoNumberFormat.java
format ( double number ) returns a formatted String representation of number
String
getPercentInstance ( ) static method that creates a format object for printing percentages
NumberFormat
getCurrencyInstance ( ) static method that creates a format object for printing numbers as money
NumberFormat
Return type Method name and argument list
CS201 Home Page
The DecimalFormat Class
- Constructor:
- Pattern characters:
0 required digit
# optional digit, suppress if 0
. decimal point
, comma separator
% multiply by 100 and display a percent sign
- See Example 3.9 DemoDecimalFormat
DecimalFormat( String pattern )
instantiates a DecimalFormat object with the format
specified by pattern
CS201 Home Page
The Math Class Constants
PI - the value of pi
E - the base of the natural logarithm
System.out.println( Math.PI );
System.out.println( Math.E );
output is:
CS201 Home Page
Methods of the Math Class
- All methods are static
- See Examples 3.10 and 3.
pow ( double base, double exp ) returns the value of base raised to the power of exp
double
sqrt ( double a ) returns the positive square root of a
double
log ( double a ) returns the natural logarithm (in base e) of its argument.
double
abs ( dataType arg ) returns the absolute value of the argument arg , which can be a double, float, int or long.
dataTypeOfArg
Return type Method name and argument list
CS201 Home Page
The Math round Method
- Rounding rules:
- Any factional part < .5 is rounded down
- Any fractional part .5 and above is rounded up
- See Example 3.12 MathRounding.java
round ( double a ) returns the closest integer to its argument a
long
Return Method name and argument list type
CS201 Home Page
The Math min/max Methods
- Find smallest of three numbers: int smaller = Math.min( num1, num2 ); int smallest = Math.min( smaller, num3 );
- See Example 3.13 MathMinMaxMethods.java
max( dataType a, dataType b ) returns the larger of the two arguments. The arguments can be doubles, floats, ints, or longs.
dataTypeOfArgs
min( dataType a, dataType b ) returns the smaller of the two arguments. The arguments can be doubles, floats, ints, or longs.
dataTypeOfArgs
Return type Method name and argument list
CS201 Home Page
The Math random Method
- Generates a pseudorandom number (appearing to be random, but mathematically calculated)
- To generate a random integer between a and up to, but not including, b : int randNum = a
- (int)( Math.random( ) * ( b - a ) );
- See Example 3.14 MathRandomNumber.java
random ( ) returns a random number greater than or equal to 0 and less than 1
double
Return Method name and argument list type
CS201 Home Page
JOptionPane static Methods
showMessageDialog ( Component
parent, Object message )
pops up an output dialog box with
message displayed
void
showInputDialog ( Component
parent, Object prompt )
pops up an input dialog box, where
prompt asks the user for input.
String
Return Method name and argument list
value
CS201 Home Page
- Provide the user with clear prompts for
input.
- Prompts should use words the user
understands and should describe the data
requested and any restrictions on valid input
values.
Enter your first and last name
or
Enter an integer between 0 and 10
CS201 Home Page
Input Using the Scanner Class
- Provides methods for reading byte , short ,
int , long , float , double , and String data types
from the Java console
- Scanner is in the java.util package
- Scanner parses (separates) input into
sequences of characters called tokens.
- By default, tokens are separated by standard
white space characters (tab, space, newline,
etc.)
CS201 Home Page
A Scanner Constructor
Scanner scan = new Scanner( System.in );
Scanner ( InputStream source )
creates a Scanner object for reading from source.
If source is System.in , this instantiates a Scanner object
for reading from the Java console
CS201 Home Page
Scanner next… Methods
nextLine ( )
returns the remainder of the line as a
String
String
next ( )
returns the next token in the input
stream as a String
String
nextDataType ( )
returns the next token in the input
stream as a dataType. dataType can be byte,
int, short, long, float, double, or boolean
int nextInt ()
double nextDouble()
dataType
Return type Method name and argument list
CS201 Home Page
Prompting the User
- Unlike dialog boxes, the next… methods do
not prompt the user for an input value
- Use System.out.print to print the prompt,
then call the next… method.
Scanner scan = new Scanner( System.in );
System.out.print( "Enter your age > " );
int age = scan.nextInt( );
CS201 Home Page
- End your prompts with an indication that
input is expected
- Include a trailing space for readability
Backup
Java Console
System.in
Scanner
CS201 Home Page
System.in Object
Class BufferReader (returns String)
Class InputStreamReader (returns unicode characters)
Object InputStream (System.in) Returns bytes
BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in));
CS201 Home Page
Input Streams
- Stream is flow of data
- Reader at one end
- Writer at the other end
- Stream generalizes input & output
- Keyboard electronics different from disk
- Input stream makes keyboard look like a disk
Writer Stream Reader
CS201 Home Page
Input Streams: System.in
- System.in: the standard input stream
- By default, reads characters from the keyboard
- Can use System.in many ways
- Directly (low-level access)
- Through layers of abstraction (high-level access)
System.in Program
CS201 Home Page
InputStreamReader.read() an InputStreamReader object
InputStream.read()
'f','i','r','s','t','\n','1','2','3','\n','4','2',' ','5','8','\n', ...
System.in stream
"first"
BufferedReader.readLine() a BufferedReader object
Input Streams: Read Strings
- Next, wrap InputStreamReader object in BufferedReader
object
InputStreamReader anInputStreamReader
= new InputStreamReader(System.in);
BufferedReader inStream = new BufferedReader(anInputStreamReader);
CS201 Home Page
Input Streams: Read Strings
Can combine these two statements
BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in));
InputStreamReader & BufferedReader in java.io.*
Must import java.io.*;
Skeleton for reading
import java.io.*; class ClassName { public static void main(String[] args) throws java.io.IOException { // Create a buffered input stream and attach it to standard // input BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in)); ... } }
CS201 Home Page
Input Streams: Read Strings
- Methods in BufferedReader
- read(): Use same as System.in.read()
- readLine(): Returns complete line typed by user
- Example: Read user's name // Reads a user's first name, middle initial, // and last name. Demonstrates use of InputStreamReader, // BufferedReader and the readLine() method. import java.io.*; class ReadInputAsString { public static void main(String[] args) throws java.io.IOException { String firstName, lastName; char middleInitial; // Create an input stream and attach it to the standard input stream BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in));
CS201 Home Page
Input Streams: Read Strings
// Read a line from the user as a String
System.out.print("Enter your first name: ");
System.out.flush();
firstName = inStream.readLine();
// Read a character from the user
System.out.print("Enter your middle initial and last
name: ");
System.out.flush();
middleInitial = (char) inStream. read ();
// Read a line from the user as a String
lastName = inStream.readLine();
// Display the strings
System.out.println();
System.out.println("Your name is " + firstName + " "
+ middleInitial + ". " + lastName);
Enter your first name: Linda Enter your middle initial and last name: EJones
Your name is Linda E. Jones
CS201 Home Page
Input Streams: Read Numbers
keyboard (int, double, ...)
- Define a NumberFormat object
- Define BufferedReader object
- Use BufferedReader object to Read response as a string
- Use NumberFormat object to parse string into Number object
- Convert Number object to primitive type
InputStreamReader.read() an InputStreamReader object
InputStream.read()
'1','2','3','\n','4','2',' ','5','8','\n', ...
System.in stream
"123"
BufferedReader.readLine() a BufferedReader object
NumberFormatter.parse()
Number(123)
Number.intValue()
123 CS201 Home Page
Input Streams: Read Numbers
- Code to read a number from keyboard (int, double, ...)
- Define a NumberFormat object NumberFormat aNumberFormatter = NumberFormat.getInstance();
- Define BufferedReader object BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in));
- Read response as a string System.out.print("Enter an integer: "); System.out.flush(); String response = inStream.readLine();
- Use NumberFormat object to parse string into Number object Number aNumberObject = aNumberFormatter.parse(response);
- Convert Number object to primitive type int intNumber = aNumberObject.intValue();
CS201 Home Page
Input Streams: Read Numbers
- Can combine reading, parsing, conversion steps import java.io.*; import java.text.NumberFormat; class ReadAnInt2 { public static void main(String[] args) throws java.io.IOException, java.text.ParseException { // Create an input stream and attach it to the standard input stream BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in)); // Create a number formatter object NumberFormat aNumberFormatter = NumberFormat.getInstance(); System.out.print("Enter an integer: "); // Read the response from the user, convert to Number,then convert to int int intNumber = aNumberFormatter.parse(inStream.readLine()).intValue(); System.out.println("You typed " + intNumber); } }
Note ParseException!