Java Methods and Classes

advertisement
Java Methods and Classes
Instructor: Sergey Goldman
Includes modified slides from Deitel “Java How to Program”
Multiple editions
1
Introduction: Methods
– Java api http://docs.oracle.com/javase/7/docs/api/
– Methods modularize a program by separating its tasks into selfcontained units
• Statements in method bodies
– Written only once
– Hidden from other methods
– Reused from several locations in a program
• Divide-and-conquer approach
– Constructing programs from small, simple pieces
• Software reusability
– Use existing methods as building blocks to create new programs
– every method should be limited to performing a single, welldefined task, and the name of the method should express that task
effectively
2
Calling other Classes/Methods
Hiding” of implementation details promotes good software engineering.
3
Static Methods
• Sometimes a method performs a task that does not depend on the contents
of any object
– Applies to the class in which it’s declared as a whole
– Known as a static method or a class method
• It’s common for classes to contain convenient static methods to perform
common tasks
• To declare a method as static, place the keyword static before the return
type in the method’s declaration
4
Static Methods cont
• Calling a static method
ClassName.methodName(arguments)
Class Math is part of the java.lang package, which is implicitly
imported by the compiler, so it is not necessary to import class Math to
use its methods
• Class Math provides a collection of static methods that enable you to
perform common mathematical calculations
• Method arguments may be constants, variables or expressions
5
java.lang.Math
Method
Description
Example
abs( x )
absolute value of x
ceil( x )
rounds x to the smallest integer not
less than x
abs( 23.7 ) is 23.7
abs( 0.0 ) is 0.0
abs( -23.7 ) is 23.7
ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0
cos( x )
trigonometric cosine of x (x in radians)
cos( 0.0 ) is 1.0
exp( x )
exponential method ex
exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
floor( x )
rounds x to the largest integer not greater Floor( 9.2 ) is 9.0
than x
floor( -9.8 ) is -10.0
log( x )
natural logarithm of x (base e)
log( Math.E ) is 1.0
log( Math.E * Math.E ) is 2.0
max( x, y ) larger value of x and y
max( 2.3, 12.7 ) is 12.7
max( -2.3, -12.7 ) is -2.3
min( x, y ) smaller value of x and y
min( 2.3, 12.7 ) is 2.3
min( -2.3, -12.7 ) is -12.7
pow( x, y ) x raised to the power y (i.e., xy)
pow( 2.0, 7.0 ) is 128.0
pow( 9.0, 0.5 ) is 3.0
sin( x )
trigonometric sine of x (x in radians)
sin( 0.0 ) is 0.0
sqrt( x )
square root of x
sqrt( 900.0 ) is 30.0
tan( x )
trigonometric tangent of x (x in radians)
tan( 0.0 ) is 0.0
6
static and final Methods
• Math fields for common mathematical constants
– Math.PI (3.141592653589793)
– Math.E (2.718281828459045)
• Declared in class Math with the modifiers public, final and static
– public allows you to use these fields in your own classes
– A field declared with keyword final is constant—its value cannot change after
the field is initialized
– PI and E are declared final because their values never change
• A field that represents an attribute is also known as an instance variable —each
object (instance) of the class has a separate instance of the variable in memory
• Fields for which each object of a class does not have a separate instance of the field
are declared static and are also known as class variables
• All objects of a class containing static fields share one copy of those fields
• Together the class variables (i.e., static variables) and instance variables represent
7
the fields of a class
static
and final in Java
private final int j;
–
–
The value must be assigned ONCE, either in the declaration or in each constructor. It is
NOT automatically assigned a value of 0.
It is not static, there is a distinct value for each instance object, so it makes sense that it must
be assigned in the constructor
private static int k;
–
The value may be assigned from anywhere in this class. Since it is not final, the value may
be assigned any number of times, but since it is static, this value is stored at the class-level
and universally available to all instances. If left unassigned, it is assumed to be 0
private static final int i;
–
The value must be assigned ONCE, either here in the declaration or in a “static” class-level
block. It is NOT automatically assigned a value of 0
8
static
and final in Java (cont)
• “final”: per-instance value, must be assigned once per instance
• “final” + “static”: per-class value, must be assigned once per class
• “static”: per-class value, can be assigned any number of times per
class
[neither modifier]: per-instance value, can be assigned any number
of times per instance
• Before Java can create an instance of a class, it must first load
and initialize that class. One step of class initialization is
assigning values to all its static fields. If they’re static and
final, those values can’t change once they’re assigned
9
public static void
main(String[] args)
• Why is method main declared static?
– The JVM attempts to invoke the main method of the
class you specify—when no objects of the class have
been created
– Declaring main as static allows the JVM to invoke
main without creating an instance of the class
10
method parameters
• Multiple parameters are specified as a comma-separated list
• There must be one argument in the method call for each parameter
(sometimes called a formal parameter) in the method declaration
• Each argument must be consistent with the type of the
corresponding parameter
11
java.util.Scanner Inputs
java.lang
System.in – InputStream
System.out – PrintStream
System.err – PrintStream
Scanner
- defaults from the keyboard
- defaults to the screen
- defaults to the screen
• text scanner which can parse primitive types and strings
• Tokenizes input using a delimiter pattern, which by default matches
whitespace
• The resulting tokens may then be converted into values of different
types using the various next methods
• Resides in the java.util package
• Can wrap a Scanner around an InputStream, i.e., System.in
to read console input (keyboard) by
Scanner input = new Scanner(System.in);
• A Scanner can also be wrapped around a File object to read from a
text file
12
Scanner example
Instantiate
Scanner myScanner = new Scanner(System.in);
Read an entire line of text
String input = myScanner.nextLine();
Read an individual token, i.e., int
int i = scanner.nextInt();
import java.util.*;
public class ScannerDemo {
public static void main(String[] args) {
int age;
String name;
Scanner myScanner = new Scanner(System.in);
System.out.println("Enter first and last name: ");
name = myScanner.nextLine();
System.out.println("How old are you? ");
age = myScanner.nextInt();
System.out.println(name + '\t' + age);
}
}
13
Scanner error handling
What if next input isn’t an int?
•
Scanner provide the ability to look at the next token in the input stream before we actually read it into
our program
– hasNextInt()
– hasNextDouble()
– hasNext()
–
etc…
if (myScanner.hasNextInt()) {
age = myScanner.nextInt();
}
else {
age = 20;
String junk = myScanner.next();
}
----- OR ----try {
age = myScanner.nextInt();
}
catch(InputMismatchException e) {
age = 20;
}
14
1
2
// Fig. 6.3: MaximumFinder.java
// Programmer-declared method maximum.
3 import java.util.Scanner;
4
5 public class MaximumFinder
6 {
7
// obtain three floating-point values and locate the maximum value
8
public void determineMaximum()
9
{
10
// create Scanner for input from command window
11
Scanner input = new Scanner( System.in );
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// obtain user input
System.out.print(
"Enter three floating-point values separated by spaces: " );
double number1 = input.nextDouble(); // read first double
double number2 = input.nextDouble(); // read second double
double number3 = input.nextDouble(); // read third double
Call method
maximum
// determine the maximum value
double result = maximum( number1, number2, number3 );
// display maximum value
System.out.println( "Maximum is: " + result );
} // end method determineMaximum
Display
maximum value
26
MaximumFinder.java
15
(1 of 2)
27
// returns the maximum of its three double parameters
28
public double maximum( double x, double y, double z )
29
{
30
Declare the maximum method
double maximumValue = x; // assume x is the largest to start
31
32
// determine whether y is greater than maximumValue
33
if ( y > maximumValue )
34
maximumValue = y;
Compare y and maximumValue
35
36
// determine whether z is greater than maximumValue
37
if ( z > maximumValue )
38
maximumValue = z;
Compare z and maximumValue
39
40
return maximumValue;
41
} // end method maximum
Return the maximum value
42 } // end class MaximumFinder
MaximumFinder.java
16
(1 of 2)
1
// Fig. 6.4: MaximumFinderTest.java
2
// Application to test class MaximumFinder.
3
4
public class MaximumFinderTest
5
{
6
// application starting point
7
public static void main( String args[] )
8
{
Create a MaximumFinder
object
9
MaximumFinder maximumFinder = new MaximumFinder();
10
maximumFinder.determineMaximum();
11
Call the determineMaximum
method
} // end main
12 } // end class MaximumFinderTest
Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35
Enter three floating-point values separated by spaces: 5.8 12.45 8.32
Maximum is: 12.45
Enter three floating-point values separated by spaces: 6.46 4.12 10.54
Maximum is: 10.54
MaximumFinderTest.java
17
18
String operations
• String concatenation
– Assemble String objects into larger strings with operators + or +=
– When both operands of operator + are Strings, operator + creates a new
String object
– characters of the right operand are placed at the end of those in the left operand
• Every primitive value and object in Java has a String representation
• When one of the + operator’s operands is a String, the other is converted to a
String, then the two are concatenated
• If a boolean is concatenated with a String, the boolean is converted to the String
"true" or "false“
• All objects have a toString() method that returns a String representation of the
object
• It is a syntax error to break a String literal across multiple lines in a program. If a
String does not fit on one line, split the String into several smaller Strings and
use concatenation to form the desired String
19
+ operator
Confusing the + operator used for string concatenation with the + operator
used for addition can lead to strange results
Java evaluates the operands of an operator from left to right
Ex (again):
int y = 5, the expression "y + 2 = " + y + 2 results in the string
"y + 2 = 52", not "y + 2 = 7", because first the value of y (5) is
concatenated with the string "y + 2 = ", then the value 2 is
concatenated with the new larger string "y + 2 = 5"
The expression "y + 2 = " + (y + 2) produces the desired result
"y + 2 = 7"
20
Method call
Three ways:
1. Using a method name by itself to call another method of the same class
2. Using a variable that contains a reference to an object, followed by a dot
(.) and the method name to call a method of the referenced object
3. Using the class name and a dot (.) to call a static method of a class
• A non-static method can call any method of the same class directly and
can manipulate any of the class’s fields directly
• A static method can call only other static methods of the same class
directly and can manipulate only static fields in the same class directly
– To access the class’s non-static members, a static method must use a
reference to an object of the class
21
Method return
• Three ways to return control to the statement that calls a method:
1. When the program flow reaches the method-ending right brace
2. When the following statement executes
return;
3.
When the method returns a result with a statement like
return expression;
Re-declaring a method parameter as a local variable in the method’s body is a
compilation error
Forgetting to return a value from a method that should return a value is a
compilation error.
If a return value type other than void is specified, the method must contain a
return statement that returns a value consistent with the method’s return-valuetype.
Returning a value from a method whose return type has been declared void
is a compilation error
22
Methods Examples
public int storage(String s) {
return s.length() * 2;
}
private boolean flag() {
return true;
}
protected float naturalLogBase() {
return 2.718f;
}
public void nothing() {
return;
}
void nothing2() {}
23
Method-Call Stack and Activation Records
• Stack data structure
– Analogous to a pile of dishes. A dish is placed on the pile at the top (referred to as pushing
the dish onto the stack)
– A dish is removed from the pile from the top (referred to as popping the dish off the stack)
• Last-in, first-out (LIFO) data structures
– The last item pushed (inserted) on the stack is the first item popped (removed) from the stack
• When a program calls a method, the called method must know how to return to
its caller
– The return address of the calling method is pushed onto the program-execution
(or method-call) stack
• If a series of method calls occurs, the successive return addresses are pushed onto
the stack in LIFO
• The program-execution stack also contains the memory for the local variables used
in each invocation of a method during a program’s execution
– Stored as a portion of the program-execution stack known as the activation record or stack
frame of the method call
24
Method-Call Stack and Activation Records cont
• When a method call is made, the activation record for that method call is
pushed onto the program-execution stack
• When the method returns to its caller, the method’s activation record is
popped off the stack and those local variables are no longer known to the
program
• If more method calls occur than can have their activation records stored on
the program-execution stack, an error known as a stack overflow occurs
• Functional programming language handle it better
• Java stack is shallow (clone() method returns a shallow copy of this Stack.
(The elements themselves are not cloned.))
25
StackOverflow Examples
public class StackOverflowExample {
public static void main(String[] args)
{
(new StackOverflowExample()).doIt();
}
public void doIt()
{
//call another one
doIt2();
}
public void doIt2()
{
doIt();
}
}
Exception in thread "main" java.lang.StackOverflowError
at StackOverflowExample.doIt2(StackOverflowExample.java:17)
at StackOverflowExample.doIt(StackOverflowExample.java:12)
at StackOverflowExample.doIt2(StackOverflowExample.java:17)
at StackOverflowExample.doIt(StackOverflowExample.java:12)
Another example: int[] x = new int[1000000000];
26
(Review) Promotion and Casting
• Argument promotion
– Converting an argument’s value, if possible, to the type that the method expects to
receive in its corresponding parameter
• Conversions may lead to compilation errors if Java’s promotion rules are not satisfied
• Promotion rules
– specify which conversions are allowed
– apply to expressions containing values of two or more primitive types and to
primitive-type values passed as arguments to methods
– Each value is promoted to the “highest” type in the expression
• In cases where information may be lost due to conversion, the Java compiler
requires you to use a cast operator to explicitly force the conversion to occur—
otherwise a compilation error occurs
Type
Valid promotions
double
float
long
int
char
short
byte
boolean
None
double
float or double
long, float or double
int, long, float or double
int, long, float or double (but not char)
short, int, long, float or double (but not char)
None (boolean values are not considered to be numbers in Java)
27
Java API Packages
Java contains many predefined classes that are grouped into categories of related
classes called packages. A great strength of Java is the Java API’s thousands of
classes.
Key packages














java.lang
java.awt
java.util
java.util.concurrent
java.text
javax.swing
javax.swing.event
java.io
java.net
java.sql
java.xml
java.xml.ws
javax.media
. . .
28
Random
• Simulation and game playing
– Class Random (package java.util)
– static method random of class Math
• Objects of class Random can produce random boolean, byte, float, double,
int, long and Gaussian values
• Math method random can produce only double values in the range
0.0 <= x < 1.0
• Class Random produces pseudorandom numbers
– A sequence of values produced by a complex mathematical calculation
– The calculation uses the current time of day to seed the random-number
generator
• The range of values produced directly by Random method nextInt often differs
from the range of values required in a particular Java application
• Random method nextInt that receives an int argument returns a value from 0 up
to, but not including, the argument’s value
29
Random Ex.
• Rolling a Six-Sided Die (1,2,3,4,5,6)
face = 1 + randomNumbers.nextInt( 6 );
– The argument 6—called the scaling factor —represents the
number of unique values that nextInt should produce (0–5)
– This is called scaling the range of values
– A six-sided die has the numbers 1–6 on its faces, not 0–5
– We shift the range of numbers produced by adding a shifting
value—in this case 1—to our previous result
– The shifting value (1) specifies the first value in the desired range
of random integers
30
1
// Fig. 6.7: RandomIntegers.java
2
// Shifted and scaled random integers.
3
import java.util.Random; // program uses class Random
4
Import class Random from the java.util package
5
public class RandomIntegers
6
{
7
public static void main( String args[] )
8
{
Create a Random object
9
Random randomNumbers = new Random(); // random number generator
10
int face; // stores each random integer generated
1.
2.
3.
RandomIntegers
.java
(1 of 2)
11
12
// loop 20 times
13
for ( int counter = 1; counter <= 20; counter++
)
Generate
14
{
15
// pick random integer from 1 to 6
16
face = 1 + randomNumbers.nextInt( 6 );
a random die roll
17
18
System.out.printf( "%d
", face ); // display generated value
19
20
// if counter is divisible by 5, start a new line of output
21
if ( counter % 5 == 0 )
22
23
24
System.out.println();
} // end for
} // end main
25 } // end class RandomIntegers
31
1
5
4
3
6
1
6
6
5
2
4
1
5
2
3
4
3
6
4
6
4
5
2
2
6
5
2
2
2
1
2
6
2
2
6
2
6
3
1
4
Two different sets of results
containing integers in the range 1-6
RandomIntegers
.java
(2 of 2)
32
Generalized Scaling and Shifting of Random Numbers
•
To generate a random number in certain sequence or range
– Use the expression
shiftingValue + differenceBetweenValues *
randomNumbers.nextInt(scalingFactor)
where:
• shiftingValue is the first number in the desired range of values
• differenceBetweenValues represents the difference between
consecutive numbers in the sequence
• scalingFactor specifies how many numbers are in the range
33
Random-Number Repeatability for Testing and Debugging
• To get a Random object to generate the same sequence of random
numbers every time the program executes, seed it with a certain
value
– When creating the Random object:
Random randomNumbers = new Random(seedValue);
– Use the setSeed method:
randomNumbers.setSeed(seedValue);
– seedValue should be an argument of type long
• While a program is under development, create the Random object with a
specific seed value to produce a repeatable sequence of random numbers
each time the program executes.
• If a logic error occurs, fix the error and test the program again with the same
seed value-this allows you to reconstruct the same sequence of random
numbers that caused the error.
• Once the logic errors have been removed, create the Random object without
using a seed value, causing the Random object to generate a new sequence
34
of random numbers each time the program executes
enum type
• An enumeration in its simplest form declares a set of constants
represented by identifiers
– Special kind of class that is introduced by the keyword enum and
a type name
– Braces delimit an enum declaration’s body
– Inside the braces is a comma-separated list of enumeration
constants, each representing a unique value
– The identifiers in an enum must be unique
– Variables of an enum type can be assigned only the constants
declared in the enumeration
– Use only uppercase letters in the names of constants. This
makes the constants stand out in a program and reminds the
programmer that enumeration constants are not variables
– Using enumeration constants (like Status.WON, Status.LOST and
Status.CONTINUE) rather than literal integer values (such as 0, 1
and 2) can make programs easier to read and maintain
35
enum type cont
• Why Some Constants Are Not Defined as enum Constants
– Java does not allow an int to be compared to an enumeration
constant
– Java does not provide an easy way to convert an int value to a
particular enum constant
– Translating an int into an enum constant could be done with a
separate switch statement
– This would be cumbersome and not improve the readability of the
program (thus defeating the purpose of using an enum)
36
Scope of Declarations
• The scope of a declaration is the portion of the program that can
refer to the declared entity by its name:
• Java Language Specification, Section 6.3: Scope of a Declaration
– java.sun.com/docs/books/jls/third_edition/html/names.html#103228
• Basic scope rules:
– The scope of a parameter declaration is the body of the method in which
the declaration appears
– The scope of a local-variable declaration is from the point at which the
declaration appears to the end of that block
– The scope of a local-variable declaration that appears in the initialization
section of a for statement’s header is the body of the for statement and
the other expressions in the header
– A method or field’s scope is the entire body of the class
• Any block may contain variable declarations
• If a local variable or parameter in a method has the same name as a field of
the class, the field is “hidden” until the block terminates execution—this is
called shadowing
37
Scope of Declarations cont
A compilation error occurs when a local variable is declared more than
once in a method
Use different names for fields and local variables to help prevent
subtle logic errors that occur when a method is called and a local
variable of the method shadows a field of the same name in the class
38
1
// Fig. 6.11: Scope.java
2
// Scope class demonstrates field and local variable scopes.
3
4
public class Scope
5
{
6
// field that is accessible to all methods of this class
7
private int x = 1;
Scope.java
(1 of 2)
8
9
// method begin creates and initializes local variable x
10
// and calls methods useLocalVariable and useField
11
public void begin()
12
{
13
Shadows field x
int x = 5; // method's local variable x shadows field x
14
15
System.out.printf( "local x in method begin is %d\n", x );
16
17
useLocalVariable(); // useLocalVariable has local x
18
useField(); // useField uses class Scope's field x
19
useLocalVariable(); // useLocalVariable reinitializes local x
20
21
useField(); // class Scope's field x retains its value
Display value of
local variable x
39
22
23
System.out.printf( "\nlocal x in method begin is %d\n", x );
} // end method begin
24
25
// create and initialize local variable x during each call
26
public void useLocalVariable()
27
{
28
Shadows field x
int x = 25; // initialized each time useLocalVariable is called
Scope.java
(2 of 2)
29
30
System.out.printf(
31
"\nlocal x on entering method useLocalVariable is %d\n", x );
32
++x; // modifies this method's local variable x
33
System.out.printf(
34
35
"local x before exiting method useLocalVariable is %d\n", x );
Display value of
local variable x
} // end method useLocalVariable
36
37
// modify class Scope's field x during each call
38
public void useField()
39
{
40
41
System.out.printf(
"\nfield x on entering method useField is %d\n", x );
42
x *= 10; // modifies class Scope's field x
43
System.out.printf(
44
45
Display value of
field x
"field x before exiting method useField is %d\n", x );
} // end method useField
46 } // end class Scope
40
1
// Fig. 6.12: ScopeTest.java
2
// Application to test class Scope.
3
4
public class ScopeTest
5
{
6
// application starting point
7
public static void main( String args[] )
8
{
9
Scope testScope = new Scope();
10
testScope.begin();
11
} // end main
12 } // end class ScopeTest
local x in method begin is 5
local x on entering method useLocalVariable is 25
local x before exiting method useLocalVariable is 26
field x on entering method useField is 1
field x before exiting method useField is 10
local x on entering method useLocalVariable is 25
local x before exiting method useLocalVariable is 26
field x on entering method useField is 10
field x before exiting method useField is 100
local x in method begin is 5
ScopeTest.java
41
Method Overloading
Methods of the same name declared in the same class
Must have different sets of parameters
• Compiler selects the appropriate method to call by examining the
number, types and order of the arguments in the call
• Used to create several methods with the same name that perform
the same or similar tasks, but on different types or different numbers
of arguments
42
Method Overloading (cont)
• Distinguishing Between Overloaded Methods
– The compiler distinguishes overloaded methods by their
signatures —the methods’ names and the number, types and
order of their parameters.
• Return types of overloaded methods
– Method calls cannot be distinguished by return type
• Overloaded methods can have different return types if the methods
have different parameter lists.
• Overloaded methods need not have the same number of
parameters.
43
Method overloading (more)
import java.io.*;
public class MethodOverloading {
public static void main(String[] args) {
}
public void method1(int x, float y) {};
public void method1(int x) {};
public void method1(int x, int z, float y) {};
/* illegal */
//public void method1(int x, float y) {};
/* illegal */
//public int method1(int x, float y) {
return 1;
}
/* illegal */
//public void method1(int x, float y) throws IOException {};
/* illegal */
//private void method1(int x, float y) {};
}
44
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Fig. 6.13: MethodOverload.java
// Overloaded method declarations.
public class MethodOverload
Correctly calls the
{
// test overloaded square methods
public void testOverloadedMethods()
{
System.out.printf( "Square of integer 7 is %d\n", square( 7 ) );
System.out.printf( "Square of double 7.5 is %f\n", square( 7.5 ) );
} // end method testOverloadedMethods
// square method with int argument
Correctly calls the
public int square( int intValue )
{
System.out.printf( "\nCalled square with int argument: %d\n",
intValue );
return intValue * intValue;
} // end method square with int argument
“square of int” method
“square of double” method
Declaring the “square of
int” method
// square method with double argument
public double square( double doubleValue )
{
System.out.printf( "\nCalled square with double argument: %f\n",
doubleValue );
return doubleValue * doubleValue;
} // end method square with double argument
} // end class MethodOverload
Declaring the “square of
double” method
MethodOverload.java
45
1
// Fig. 6.14: MethodOverloadTest.java
2
// Application to test class MethodOverload.
3
4
public class MethodOverloadTest
5
{
6
public static void main( String args[] )
7
{
8
MethodOverload methodOverload = new MethodOverload();
9
methodOverload.testOverloadedMethods();
10
} // end main
11 } // end class MethodOverloadTest
Called square with int argument: 7
Square of integer 7 is 49
Called square with double argument: 7.500000
Square of double 7.5 is 56.250000
MethodOverloadTest.java
46
1
// Fig. 6.15: MethodOverloadError.java
2
// Overloaded methods with identical signatures
3
4
5
// cause compilation errors, even if return types are different.
6
{
7
8
9
public class MethodOverloadError
MethodOverload
Error.java
// declaration of method square with int argument
public int square( int x )
{
return x * x;
10
11
12
}
13
14
15
16
// second declaration of method square with int argument
// causes compilation error even though return types are different
public double square( int y )
{
Same method signature
17
return y * y;
18
}
19 } // end class MethodOverloadError
MethodOverloadError.java:15: square(int) is already defined in
MethodOverloadError
public double square( int y )
^
Compilation
1 error
error
47
Classes
•
•
Early rudimentary languages had only arrays
– all elements had to be of the same type
Then languages introduced structures (called records, or structs)
– allowed different data types to be grouped
– Note Java has no struct
•
Then Abstract Data Types (ADTs) became popular
– grouped operations along with the data
• A class consists of
– a collection of fields, or variables, very like the named fields
of a struct
– all the operations (called method, or functions) that can be
performed on those fields
• A class is like a type; it describes objects
• The objects are like values of that type
48
More on Classes
• The class is the fundamental concept in JAVA (and other OOPLs)
• A class describes some data object(s), and the operations (or
methods) that can be applied to those objects (algebra)
• Every object and method in Java belongs to a class
• Classes have data (fields) and code (methods) and classes
(member classes or inner classes)
• Static methods and fields belong to the class itself
• Others belong to instances
49
The Java class hierarchy
•
•
•
•
Classes are arranged in a hierarchy
– The root, or topmost, class is Object
All classes descend from this single root
Every class but Object has a (one) superclass - No multiple inheritance!
A class may have subclasses
Each class inherits all the fields and methods of its superclasses (or socalled parent or base or super class)
50
The Java class hierarchy
class Person {
String name; /* field */
int age;
/* field */
void birthday ( ) { /* method */
age++;
System.out.println (name + “ is now “ + age);
}
}
Child or Derived class:
class Driver extends Person {
long driversLicenseNumber= 0;
Date expirationDate= null;
}
51
Scoping
As in C/C++, scope is determined by the placement of curly braces {}.
A variable defined within a scope is available only to the end of that scope.
{
{
int x = 12;
/* only x available */
}
int y = 96;
/* only y available */
}
/* x an y are not available */
{
int x = 12;
{
int x = 96; /* illegal */
}
}
This is OK in C/C++ but not in Java
52
Creating and using an object
Person john;
john= new Person();
john.name= "John Smith";
john.age= 37;
Person mary= new Person();
mary.name= "Mary Brown";
mary.age= 33;
mary.birthday();
53
An array is an object
Person mary= new Person();
int[] myArray= new int[5];
int[] myArray= {1, 4, 9, 16, 25};
String[] languages= {"Prolog", "Java"};
Since arrays are objects they are NOT allocated on stack, but
dynamically (more later)
Arrays, like all objects, are subject to garbage collection when
no more references remain (so fewer memory leaks)
54
Scope of Objects
• Java objects don’t have the same lifetimes as primitives
• When you create a Java object using new, it hangs around past the
end of the scope.
Here, the scope of name s is delimited by the {}s but the String object
hangs around until GC’d
{
String s = new String("a string");
} /* end of scope */
55
The static keyword
•
Java methods and variables can be declared static
•
These exist independent of any object
•
This means that a Class’s static methods can be called even if no objects of that
class have been created and static data is “shared” by all instances (i.e., one rvalue
per class instead of one per instance)
class StaticTest {
static int i = 47;
}
StaticTest st1 = new StaticTest();
StaticTest st2 = new StaticTest();
// st1.i == st2.i == 47
StaticTest.i++; // or st1.i++ or st2.i++
// st1.i == st2.i == 48
56
Array Operations
•
•
•
Subscripts always start at 0 as in C
Subscript checking is done automatically
Certain operations are defined on arrays of objects, as for other classes e.g.
myArray.length == 5
•
Example: Echo.java (Java < 1.5)
class Echo {
public static void main(String[] args) {
for (int i=0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}
C >javac Echo.java
C:>java Echo this is pretty silly
this
is
pretty
silly
v. 1.5 There is a Scanner class
java => 1.5 Scanner input= new Scanner(System.in);
57
Classical Example: Calculating factorial
/**
* Calculates factorial of given number non-recursively
*/
public class Factorial { /* Define a class */
public static void main(String[] args) { /* The program starts */
int input= Integer.parseInt(args[0]); /* Get the user's input */
double result= factorial(input);
/* Compute the factorial */
System.out.println(result);
/* Print out the result */
} /* The main() method ends here */
public static double factorial(int x) { /* This method computes x! */
if (x < 0)
/* Check for bad input
*/
return 0.0;
/* if bad, return 0 */
double fact= 1.0;
/* Begin with an initial value */
while(x > 1) {
fact= fact * x;
x= x - 1;
}
/*
/*
/*
/*
return fact;
Loop until x equals 1 */
multiply by x each time */
and then decrement x
*/
Jump back to the start of loop */
/* Return the result */
}
}
58
Circle.java – base class
public class Circle {
// A class field
public static final double PI= 3.14159;
// A useful constant – UPPER case convention
// An instance field
public double r;
// The radius of the circle
// A class method: just compute a value based on the arguments
public static double radiansToDegrees(double rads) {
return rads*180/PI;
}
// Two instance methods: they operate on the instance fields of an object
public double area() { // Compute the area of the circle
return PI * r * r;
}
public double circumference() { /* Compute the circumference of the circle */
return 2 * PI * r;
}
}
59
Constructors
•
Classes should define one or more methods to create or construct
instances of the class
•
Their name is the same as the class name
•
note deviation from convention that methods begin with lower case
•
Constructors are differentiated by the number and types of their
arguments
•
An example of overloading
•
If you don’t define a constructor, a default one will be created
•
Constructors automatically invoke the zero argument constructor of
their superclass when they begin
60
Circle.java with constructors
public class Circle {
public static final double PI= 3.14159; /* A constant */
public double r; /* instance field holds circle’s radius */
/* The constructor method: initialize the radius field */
public Circle(double r) {
this.r = r;
}
/* Constructor to use if no arguments */
public Circle() {
r= 1.0;
}
/* better: public Circle() {this(1.0);} */
/* The instance methods: compute values based on radius
public double circumference() {
return 2 * PI * r;
}
*/
public double area() {
return PI * r*r;
}
}
this.r refers to the r field of the class
this() refers to a constructor for the class
61
Inheritance - Extending a class
•
Class hierarchies reflect subclass-superclass (parent-child ) relations
among classes.
•
One arranges classes in hierarchies:
– A class inherits instance variables and instance methods from all its
superclasses.
•
You can specify only ONE superclass for any class.
•
When a subclass-superclass chain contains multiple instance methods with
the same signature (name, and argument types), the one closest to the
target instance in the subclass-superclass chain is the one executed.
•
•
•
All others are shadowed/overridden
Something like multiple inheritance can be done via interfaces
What’s the superclass of a class define w/o an extends clause?
Ans:…
62
PlaneCircle extends Circle
public class PlaneCircle extends Circle {
/* Automatically inherit the fields and methods of Circle,
so we only have to put the new stuff here.
New instance fields that store the center point of the circle
*/
public double cx;
public double cy;
/* A new constructor method to initialize the new fields
It uses a special syntax to invoke the Circle() constructor
*/
public PlaneCircle(double r, double x, double y) {
super(r);
// Invoke the constructor of the superclass , Circle()
this.cx= x; /* Initialize the instance field cx */
this.cy= y; /* Initialize the instance field cy */
}
/* The area() and circumference() methods are inherited from Circle A new instance method that
checks whether a point is inside the circle. Note that it uses the inherited instance field r */
public boolean isInside (double x, double y) {
double dx= x - cx, dy = y - cy;
// Distance from center
double distance=Math.sqrt(dx*dx + dy*dy);//Pythagorean theorem
return (distance < r);
//Returns true or false
63
}
}
Overloading, overwriting, and shadowing
•
Overloading
– occurs when Java can distinguish two procedures with the same name
by examining the number or types of their parameters (in the same
class)
•
Shadowing or overriding
– occurs when two procedures with the same signature (name, the same
number of parameters, and the same parameter types) are defined in
different classes, one of which is a superclass of the other.
64
Data hiding and encapsulation
•
Data-hiding or encapsulation is an important part of the OO paradigm
•
Classes should carefully control access to their data and methods in order to
hide the irrelevant implementation-level details so they can be easily changed
•
Protect the class against accidental or malicious damage
•
Keep the externally visible class simple and easy to document
•
Java has a simple access control mechanism to help with encapsulation
65
Modifiers
public
protected
private
package (default)
66
package com.oit.java.shapes;
/* Specify a package for the class */
public class Circle { /* The class is still public */
/* This is a generally useful constant, so we keep it public */
public static final double PI= 3.14159;
protected double r; /* Radius is hidden, but visible to subclasses */
/* A method to enforce the restriction on the radius
This is an implementation detail that may be of interest to subclasses
*/
protected checkRadius(double radius) {
if (radius < 0.0)
throw new IllegalArgumentException("radius may not be negative.");
}
/* The constructor method */
public Circle(double r) {
checkRadius(r);
this.r = r;
}
/* Public data accessor methods */
public double getRadius() {return r;}
public void setRadius(double r) {
checkRadius(r);
this.r= r;
}
/* Methods to operate on the instance field */
public double area() {return PI * r * r;}
public double circumference() {return 2 * PI * r;}
}
67
Abstract classes and methods
•
Abstract vs. concrete classes
•
Abstract classes can not be instantiated public abstract class Shape { }
•
An abstract method is a method w/o a body public abstract double area();
•
(Only) Abstract classes can have abstract methods
• In fact, any class with an abstract method is automatically an abstract class
public abstract class Shape {
public abstract double area();
// Abstract methods: note
public abstract double circumference();/* semicolon instead of
body. */
}
68
Implementation
class Circle extends Shape {
public static final double PI= 3.14159265358979323846;
protected double r; /* Instance data */
/* Constructor */
public Circle(double r) {
this.r = r;
}
/* Accessor */
public double getRadius() {
return r;
}
/* Implementation of area() */
public double area() {
return PI*r*r;
}
/* Implementation of circumference() */
public double circumference() {
return 2*PI*r;
}
}
69
class Rectangle extends Shape {
protected double w, h; /* Instance data */
public Rectangle(double w, double h) { /* Constructor */
this.w = w;
this.h = h;
}
/* Accessor */
public double getWidth() {
return w;
}
/* Accessor */
public double getHeight() {
return h;
}
/* Implementation of area() */
public double area() {
return w*h;
}
/* Implementation of circumference() */
public double circumference() {r
return 2*(w + h);
}
}
70
Interface
Interface is a type, just as a class is a type
Like a class, an interface defines methods
Unlike a class, an interface never implements methods; instead, classes
that implement the interface implement the methods defined by the interface
A class can implement multiple interfaces
71
Download