Cleaning up PowerPoint PPT Presentation

presentation player overlay
1 / 8
About This Presentation
Transcript and Presenter's Notes

Title: Cleaning up


1
Cleaning up!
  • Miscellaneous things of some import

2
Names
  • A name is called an identifier in Java
  • Many things can be named in Java
  • Classes
  • Variables
  • Methods
  • Names can be re-used (duplicated) if certain
    rules are followed
  • The rules make sure that a name refers to exactly
    one thing

3
Identifiers
public class SomeClass public int
foo private int fi private int fee
public void foo( int fum ) // code
missing public void foo( double fi )
// code missing
public class Client private SomeClass c
public void method() // can we
write c.fee c.foo c.foo(3) c.foo(3.0)
4
Method Overloading
  • Two methods in the same class can have the same
    name
  • Must have different parameter lists
  • May differ in the type of arguments
  • May differ in the number of arguments
  • When the name is used, the specific function must
    be determined by context.

public class SomeClass public int foo(int
x) public int foo(double x)
public int foo(int x, int y) public int
foo(String x) public int foo(Rectangle
x) public int foo(int z)
5
Summary of name reuse
  • There are no restrictions for using the same
    identifier in two separate classes.
  • There are no restrictions for using the same
    identifier to name local variables and/or
    parameters of different methods.
  • A local variable (or parameter) can have the same
    name as an instance variable of its class.
  • An instance variable and method can share the
    same name within the same class.
  • Methods can be overloaded

public class SomeClass public int
fee private int fi private int foo
public void foo( int fum ) int fo int
fee public void foo( double fi )
int fo int fum
6
Difficulty with name reuse
  • Consider the following rule
  • A local variable (or parameter) can have the same
    name as an instance variable of its class.
  • The keyword this refers to the currently active
    object. Use the keyword this as an object
    reference!

public class SomeClass public int
conundrum public void foo() int
conundrum // how to output the conundrum
instance var?
7
Recursion
  • Methods can be recursive. The method is invoked
    within the body of the method!
  • Consider the following mathematical definition of
    the factorial function
  • How could this be written in Java?

public int fact(int n) int result 1
for(int i1 iltn i) result result
i return result
public int fact(int n) if(n 0)
return 1 else return n fact(n-1)

Iterative (non recursive) solution
Recursive solution
8
Recursion
  • Consider the following mathematical definition of
    the greatest common divisor of two non-negative
    integers X and Y where X gt Y .

/ precondition x gt y / public int gcd(int x,
int y) if(y 0) return x else
return gcd(y, xy)
gcd(259, 111)
Write a Comment
User Comments (0)
About PowerShow.com