Chapter 3 Implementing Classes - PowerPoint PPT Presentation

1 / 50
About This Presentation
Title:

Chapter 3 Implementing Classes

Description:

This class is used to do the currency conversion * between a foreign currency and the US Dollar ... is worth in foreign currency. private double exchangeRate; ... – PowerPoint PPT presentation

Number of Views:58
Avg rating:3.0/5.0
Slides: 51
Provided by: ameet9
Category:

less

Transcript and Presenter's Notes

Title: Chapter 3 Implementing Classes


1
Chapter 3 Implementing Classes
2
Syntax 3.5 The return Statement
  • return expression or
  • return
  • Example
  • return balance
  • Purpose
  • To specify the value that a method returns, and
    exit the method immediately. The return value
    becomes the value of the method call expression.

3
(No Transcript)
4
(No Transcript)
5
(No Transcript)
6
Wus Template
7
Template in action
  • /
  • This class is used to do the currency
    conversion
  • between a foreign currency and the US Dollar
  • _at_author Ameet Soni
  • /

Class Comment
8
Defining the class
9
Template in action
  • /
  • This class is used to do the currency
    conversion
  • between a foreign currency and the US Dollar
  • _at_author Ameet Soni
  • /
  • public class CurrencyConverter

Class Name
10
Defining the class
11
Template in action
  • /
  • This class is used to do the currency
    conversion
  • between a foreign currency and the US Dollar
  • _at_author Ameet Soni
  • /
  • public class CurrencyConverter
  • /
  • how much 1 USD is worth in foreign currency
  • /
  • private double exchangeRate

Declaration (Data Members/Instance Fields
12
Defining the class
13
Template in action
  • /
  • This class is used to do the currency
    conversion
  • between a foreign currency and the US Dollar
  • _at_author Ameet Soni
  • /
  • public class CurrencyConverter
  • /
  • how much 1 USD is worth in foreign currency
  • /
  • private double exchangeRate
  • public CurrencyConverter()
  • exchangeRate 0
  • public CurrencyConverter(double inRate)
  • exchangeRate inRate

Constructors
14
Template in action
  • /
  • This class is used to do the currency
    conversion
  • between a foreign currency and the US Dollar
  • _at_author Dr. Caffeine
  • /
  • class CurrencyConverter
  • /
  • how much 1 USD is worth in foreign currency
  • /
  • private double exchangeRate
  • public CurrencyConverter()
  • exchangeRate 0
  • public CurrencyConverter(double inRate)
  • exchangeRate inRate
  • public void setExchangeRate (double rate )

Methods
15
Not in Book
  • In this course, there are three types of classes
    you will write

16
What's a Class? Defn 1
  • Source code that defines a new data type by
    encapsulating
  • data members
  • constructors
  • method.
  • Ex. BankAccount class we just created
  • AKA Instantiable class designed to be created
    as objects

17
  • / Stores information about one pet. /
  • public class Pet
  • / Name of the pet. /
  • private String name, kind
  • private int age
  • / Initializes a new instance.
  • _at_param n The pet's name.
  • /
  • public Pet( String n, String k, int a )
  • name n kind k age a
  • / Returns the name of this pet. /
  • public String getName() return name
  • / Changes the name of this pet.
  • _at_param newName The new name of the pet.

Data member
Constructor
Methods
18
What's a Class? Defn 2
  • Code that is written to test another class.
  • Has a main method that
  • Creates instances of the class
  • Executes methods
  • Compares the actual with expected.
  • Classes should be tested before being used in
    Java Applications.
  • Ex. Part of Assignment 1

19
  • / A Test Program. /
  • public class TestPet
  • /
  • Test Program starts here.
  • _at_param args Unused in this program.
  • /
  • public static void main( String args )
  • // Declare and create a pet
  • Pet pet1 new Pet( "George", "bird", 14 )
  • // Test the pet's information
  • testGetName( pet1, George )
  • / Tests Pet getName method. /
  • public static void testGetName( Pet pet,
  • String expectedName )

20
What's a Class? Defn 3
  • Java Application
  • Source code that uses instances of other classes
    (objects) to solve problems.
  • Must have a main method.
  • Ex. Programs you completed in A0

21
  • / A Java Application. /
  • public class PetApplication
  • /
  • Program starts here.
  • _at_param args Unused in this program.
  • /
  • public static void main( String args )
  • // Declare and create a pet
  • Pet pet1 new Pet( "George", "bird", 14 )
  • // Output the pet's information
  • display( pet1 )
  • / Prints Pet information to screen. /
  • public static void display( Pet pet )
  • System.out.println(

22
3.6 Testing Classes
  • Previous section was designing a class
  • By itself, we cannot actually run a program
  • No main() method, like most classes
  • We create instances of it in other classes
  • Idea use a test class to make sure it works
    properly before dispensing the product

23
3.6 Testing A Class
  • Test class a class with a main method that
    contains statements to test another class.
  • Typically carries out the following steps
  • Construct one or more objects of the class that
    is being tested
  • Invoke one or more methods
  • Print out one or more results
  • Verify output is correct and program behaves as
    expected

24
Youve done this
  • A0 asked you to make test classes
  • Perimeter.java tested getHeight() and getWidth()
    methods
  • MoveTester tested the translate() method

25
  • Details for building the program vary. In most
    environments, you need to carry out these steps
  • Write a test program for the methods
  • Include the class being tested in the project
  • Run the test program

26
  • /
  • A class to test the BankAccount class.
  • /
  • public class BankAccountTester
  • /
  • Tests the methods of the BankAccount class.
  • _at_param args not used
  • /
  • public static void main(String args)
  • BankAccount harrysChecking new
    BankAccount()
  • harrysChecking.deposit(2000)
  • harrysChecking.withdraw(500)
  • System.out.println(harrysChecking.getBalance())

27
3.7 Categories of Variables
  • Categories of variables
  • Instance fields (balance in BankAccount)
  • Local variables (newBalance in deposit method)
  • Parameter variables (amount in deposit method)
  • Share the same properties of declaring and
    creating
  • Differ in their lifetime (AKA scope)

28
Instance Field
  • An instance field belongs to an object
  • AKA Instance variable
  • Each object has its own copy of the instance
    field
  • The fields stay alive until no method uses the
    object any longer
  • More specifically, until the object no longer
    exists

29
Garbage
  • In Java, the garbage collector periodically
    reclaims objects when they are no longer used
  • If no variables reference to the object anymore,
    it can no longer be used and is collected

30
Local Variables
  • Local and parameter variables belong to a method
  • You declare them and create within the method
  • When method is done executing, variable is thrown
    out
  • EVERYTIME the method is executed, a new copy of
    any variables is created, values do not carry over

31
Initialization with scope
  • Instance fields are initialized to a default
    value, but you must initialize local variables
  • Default values for numbers is 0
  • Objects is null
  • COMMON ERROR forgetting to create objects for
    instance fields, declaration leaves it at null
  • Not an issue with parameter variables

32
Parameter variables
  • Parameter variables are initialized to the values
    that are passed to them
  • Maintain same lifetime as local variables
  • Only difference is that they receive values
    automatically

33
Lifetime Of Variables
  • harrysChecking.deposit(500)
  • double newBalance balance amount
  • balance newBalance

34
(No Transcript)
35
3.8 Implicit and Explicit Method Parameters
  • The implicit parameter of a method is the object
    on which the method is invoked
  • Why is this important?
  • When a method is invoked, and an instance field
    is used, how does it know which object it belongs
    to?

36
  • Use of an instance field name in a method denotes
    the instance field of the implicit parameter
  • public void withdraw(double amount) double
    newBalance balance - amount balance
    newBalance

37
  • balance is the balance of the object to the left
    of the dot
  • momsSavings.withdraw(500)
  • means
  • double newBalance momsSavings.balance -
    amountmomsSavings.balance newBalance

38
Implicit Parameters and this
  • Every method has one implicit parameter
  • The implicit parameter is always called this
  • The method knows what object called it based on a
    reference, but does not know/care about the
    identifier name
  • E.g. you cannot say momsSavings.balance in the
    class, because momsSavings is a local variable of
    another class
  • Exception Static methods do not have an implicit
    parameter (more on Chapter 9)

39
Implicit Parameters and this
  • double newBalance balance amount// actually
    meansdouble newBalance this.balance amount
  • When you refer to an instance field in a method,
    the compiler automatically applies it to the this
    parameter
  • momsSavings.deposit(500)

40
Implicit Parameters and this
41
Advanced Info
  • this operator very powerful
  • Can call one constructor from another to avoid
    redundancy
  • Important goal in programming, never have
    duplicate code

42
Example without this
  • public class BankAccount
  • double balance
  • public BankAccount(double initialBalance)
  • balance initialBalance
  • public BankAccount
  • balance 0

43
Example with this
  • public class BankAccount
  • double balance
  • public BankAccount(double initialBalance)
  • balance initialBalance
  • public BankAccount
  • this(0)

44
HOW TO 3.1 Designing and Implementing a Class
  • Step 1 Find out what you are asked to do with an
    object of the class
  • What do you want to be able to do with the
    object?
  • Step 2 Specify the Public Interface
  • Convert the list from step 1 into methods, and
    the parameters (think input) they need
  • Constructors how do I want to initialize this
    object

45
HOW-TO 3.1 (cont)
  • Step 3 Document the public interface
  • Create Javadoc comments for each method and the
    class
  • Step 4 Determine instance fields
  • What information needs to be maintained?
  • Step 5 Implement
  • One at a time, from easiest to most difficult

46
HOW-TO 3.1 (cont)
  • Go back to Step 2 if implementation doesnt work
  • Step 6 Test your class

47
Note on Style 1
  • A couple ways to use curly braces
  • Option 1
  • public class SomeClass
  • Option 2
  • public class SomeClass

48
Note on Style 2
  • Book says to place instance fields at the bottom
    of a class
  • public class SomeClass
  • //constructors
  • //methods
  • //instance fields
  • Most conventions have it at the top of a class
  • public class SomeClass
  • //instance fields
  • //constructors
  • //methods

49
Note on Style 3
  • Already discussed variations on import
  • Dont use import (fully qualify all classes)
  • Import just one class (java.awt.Rectangle)
  • Import the entire package (java.awt.)

50
What is the right way?
  • You can use any of the options
  • You MUST(will grade on this) be consistent though
  • Dont use both styles of curly braces in the same
    program
Write a Comment
User Comments (0)
About PowerShow.com