Title: More about Methods
1More about Methods
- Dr. Tim Margush
- University of Akron
2Goals
- Be able to create appropriate classes to support
algorithm development - Understand cohesion, coupling, and side-effects
- Know the difference between class and instance
members and be able to apply that knowledge - Appreciate scope rules and the use of packages
3Programming With Class
- A class captures the essential attributes of and
actions related to a single concept - Class definitions are used to
- Instantiate objects
- Group related functions
- Separate 'form' from 'function'
- Bind actions to data collections
4'Form' vs. 'Function'
- The public interface of a class defines its
'form' - How it 'looks' from the outside
- What its capabilities are
- The private members hide the implementation
details 'function' and 'structure' - How it does what it does (method implementation)
- How it represents (internal data structures) the
class concept
5Classification of Classes
- Abstractions represent physical objects
- The focus is on the attributes
- Rectangle, BankAccount, Person
- Actors represent objects that perform a useful
function - The focus is on a sequence of actions or process
- Scanner, Random, FactorGenerator
- Utility classes group related methods and
constants - The focus is on calculations or values
- Math, Array, System
6Cohesion
- The degree to which the public members of a class
are related to a single purpose, concept, or
function - Strive for a high degree of cohesion
- Separate concepts deserve their own class
- Example A car has a radio and a gas pedal
- Do not simply include the details for these
objects in a Car class - Group radio related info in a Radio class
- Group acceleration related info in a GasPedal
class - Use these classes inside the Car class
7Coupling
- The degree to which two classes depend on each
other - A class depends on another if it uses its methods
- Attempt to minimize coupling
- The Car class depends upon the GasPedal and Radio
classes, however these classes do not depend on
each other - They might call methods in the Car class as well
(increasing the degree of coupling)
8Unified Modeling Language
- A graphical representation of classes/objects and
their interrelationships
B
A
Dashed line with open arrow tip indicates
dependency (coupling) "A depends on B"
9Mutable - Immutable
- An object whose state can change is a mutable
object (Rectangle) - A method that causes a change of state is a
mutator - Mutators generally return void
- An immutable object cannot be changed once
created (String) - A method that does not change the state is an
accessor - Accessors generally return a copy of internal
information
10Side-Effect
- When a method call causes a change to anything
other than the implicit object or class, a
side-effect is said to have occurred - A method that causes console output
- Couples the class with System and PrintStream
- A method that modifies a different object,
especially one belonging to a different class - Couples the two classes
11Great Expectations
- Every method should clearly state any
pre-conditions - something that is required to be
true for proper operation - Are parameter values limited in any way?
- Positive, non-null, less than 1000,
- Must something else have happened first?
- Call init() before calling this method
- Requires a successful find() operation prior to
use
12Verify Pre-Conditions?
- An Exception may be created (thrown) if any
pre-condition is not met - if (amount lt 0) throw new
RuntimeException("amount too small") - Don't test and then simply ignore illegal values
- Sometimes this is allowed by the specifications
of the method
13The Bottom Line
- A post-condition is something that is true when a
method call completes - Assuming the pre-conditions were met!
- Assuming the method is correct!
- State non-trivial post-conditions in method
documentation - Post-conditions are like a contract to be
fulfilled - Post-conditions help guide the programming
process - Post-conditions aid in program maintenance
14Be Assertive
- The assert command can be used to verify that
pre- and post-conditions are met - Assertion checking can be enabled at runtime
- java ea SomeClass
- Assert syntax
- assert condition message
- An assertion error is thrown if assertion
checking is enabled and an asserted condition
evaluates to false
15Class Variables
Class variable
- Declared using the static keyword
- Each class variable
- Is shared by all objects of the class
- Lives in the "object factory" not in an object
- Accessed from instance or class methods
- class Student
- private static int sCount 0
- private String id
- public Student()
- sCount
- id "ST"sCount
-
- public static int getCount()
- return sCount
-
Accessed from instance method
Accessed from class method
16Static Storage
static int sCount 0 String id public Student
() sCount id "ST"sCount
- int x Student.getCount()
- Student a new Student()
- Student b new Student()
- String aID a.getID()
- x Student.getCount()
0
17Instance and Class Methods
- Instance methods
- generally access at least one instance variable
- Have access to an implicit object
- Are able to access class variables
- Require an object to be invoked
- Class methods
- Cannot access instance variables
- Have no implicit object
- Can access only class variables (and parameters)
- Are usually called using the class name rather
than an object
18public final class Math
- A class with only static methods and members
- You never need Math m new Math()
- In fact, this is illegal as the constructor is
private - double x Math.E
- e Math.PI
- int n Math.max(-1,1)
- double t Math.min(Math.E, Math.PI)
- double next Math.nextUp(0.0)
19public static void main(String a)
- Why is main static?
- The command java TestApplication loads the
class and calls its method named main without
instantiating any objects of this class - Only static methods can be called in this way
- The JVM creates the class factory, but does not
create objects of that class
20Parameters and Arguments
- Methods can have 0, 1, or more parameters
- Each method call must provide arguments that
match the expected parameters in number and type
public static String makeBar(int sz, char bc)
println(Chart.makeBar(23, '')) println(Chart.mak
eBar(0)) println(Chart.makeBar('',
100)) println(Chart.makeBar(3.5, ""))
21Argument Promotion and Casting
- Arguments are promoted (if legal) to match the
formal parameter's type - Casting is required for other conversions
- public static double sqrt(double x)
- int x (int)Math.sqrt(4)
byte
short
int
long
float
double
char
Allowable primitive promotions
boolean
22Method Calls
- Method calls can be written in one of three ways
- setSize(23)
- anObject.setSize(23)
- SomeClass.setSize(23)
23Method Exits
- Control normally leaves a method in one of three
ways - Execution reaches end of method body
- A return is reached
- A return expression is reached
24Call Stack and Activation Records
- Memory for parameters and local variables is
- allocated when a method call occurs
- de-allocated when the method exits
- This allocation occurs on what is called the
run-time stack - The block of memory devoted to each active method
is called its activation record
25Runtime Stack
The constructor calls a private method in the
class
Activation record for private method
Stack grows in this direction
In main, an object is instantiated, causing a
constructor call
Activation record for constructor
Execution begins with main
Activation recordfor main
26Scope
- The scope of an identifier declaration is the
region of the program in which that identifier
can be accessed using its simple name - Local variables have local scope which begins at
the declaration and extends to the end of its
block - Variables declared in the for initialization are
restricted in scope to the context of the for
statement - A parameter's scope is it's method's body
- Class members (defined in or inherited) have
class scope, meaning they are available
throughout the entire class body
27Shadowing
- A declaration of an identifier named x within the
scope of an identifier named x shadows the first
identifier for the scope of the declaration - Access to a shadowed identifier requires
qualification
- public class Shadow
- private boolean knows
- public Shadow(boolean knows)
-
- //the parameter shadows
- //the field
- this.knowsknows
-
-
28Scope It Out
- What is the scope of the field x?
- What is the scope of the loop variable x?
- What is the scope of the parameter x?
- What is the scope of the method use?
- public class A
- private int x
- public A()
- for (int x0 xlt9 x)
- use(x)
- use(x)
-
- private void use(int x)
- this.xx
-
- public int getX()
- return x
-
29Local Variables
- You may reuse the same local variable in a method
as long as their scopes do not overlap - Overlapping scopes for local variables results in
compile error
- public class NonOverlap
- public void madness()
-
- for (int x0 xlt9 x)
- totalx
- //scope of x ends here
- double x //reuse of x - OK
- if (legal)
- int x0 //illegal overlapping
-
-
-
30Overload
- When two or more methods in a class have the same
name, they are said to be overloaded - Overloaded methods must have different parameter
lists (in number or type or order) - Together with the method name, this is referred
to as the method's signature - The compiler finds a matching signature based on
the actual arguments
31Argument Parameter Matching
- public static int less(int x, int y)
- return xlty ? x y
-
- public static long less(double x, int y)
- if (x lt y)
- return (long)x
- else
- return y
- int d less(5, (short)4)
- int e less(3.7f, 6)
- int g (int)less(6L, 3)
- int r less('a', 'b')
32Summary
- Classes are defined to capture attributes of and
actions related to a single concept - Classes should be cohesive and minimize coupling
- Classes can be mutable or immutable
- Methods can be mutators or accessors
- Pre and post conditions are important for program
development and maintenance
33Summary
- Class variables are shared by all objects of the
class while instance variables are replicated in
each object that is created - Class variables and methods are not connected to
objects - Scope rules define the extent of an identifier
declaration - Methods can be overloaded to provide custom
behavior for different types of arguments