Chapter 3 Implementing Classes - PowerPoint PPT Presentation

1 / 103
About This Presentation
Title:

Chapter 3 Implementing Classes

Description:

– PowerPoint PPT presentation

Number of Views:56
Avg rating:3.0/5.0
Slides: 104
Provided by: ameet9
Category:

less

Transcript and Presenter's Notes

Title: Chapter 3 Implementing Classes


1
Chapter 3 Implementing Classes
2
Chapter Goals
  • To become familiar with the process of
    implementing classes
  • To be able to implement simple methods
  • To understand the purpose and use of constructors
  • To understand how to access instance fields and
    local variables
  • To appreciate the importance of documentation
    comments

3
3.1
  • What is a black box?
  • Why do we call it a black box?
  • What are some instances of a black box?

4
3.1 Black Boxes
  • A black box magically does its thing
  • Hides its inner workings
  • Encapsulation the hiding of unimportant details

5
  • Not everything is hidden in a black box
  • Ways to interact with it, but all done on the
    outside
  • Interaction possibilities are well defined

6
Properties of Encapsulation
  • What is the right concept for each particular
    black box?
  • Concepts are discovered through abstraction
  • Abstraction taking away inessential features,
    until only the essence of the concept remains
  • How much does a user really need to know?

7
Example Cars
  • Black boxes in a car transmission, electronic
    control module, etc

8
Example Car
  • Users of a car do not need to understand how
    black boxes work
  • Interaction of a black box with outside world is
    well-defined
  • Drivers interact with car using pedals, buttons,
    etc.
  • Mechanic can test that engine control module
    sends the right firing signals to the spark plugs
  • For engine control module manufacturers,
    transistors and capacitors are black boxes
    magically produced by an electronics component
    manufacturer

9
Example Car
  • Encapsulation leads to efficiency
  • Mechanic deals only with car components (e.g.
    electronic control module), not with sensors and
    transistors
  • Driver worries only about interaction with car
    (e.g. putting gas in the tank), not about motor
    or electronic control module

10
Example Doorbell
  • What can we do to a doorbell?
  • Do we know how a doorbell works?
  • Models
  • Flintstones
  • Simpsons
  • Rube Goldberg Device
  • Noise

11
  • In object-oriented programming the black boxes
    from which a program is manufactured are called
    objects

12
Levels of abstraction Software Design
13
  • Old times computer programs only manipulated
    primitive types such as numbers and characters
  • Gradually programs became more complex, vastly
    increasing the amount of detail a programmer had
    to remember and maintain

14
  • Solution Encapsulate routine computations to
    software black boxes
  • Abstraction used to invent higher-level data
    types
  • In object-oriented programming, objects are black
    boxes

15
Important Concept
  • Who designs objects you use
  • Other programmers
  • What do these other objects contains
  • Other Objects
  • Developed by other programmers, who used other
    objects, etc.
  • Lesson Multiple levels of abstraction
  • Almost always, you will be designing an
    abstraction while simultaneously using another one

16
  • Encapsulation Programmer using an object knows
    about its behavior, but not about its internal
    structure
  • In software design, you can design good and bad
    abstractions understanding what makes good
    design is an important part of the education of a
    software engineer
  • First, define behavior of a class then,
    implement it

17
3.1
  • Chapter 2 you used objects
  • Analogous to engineer who puts final parts
    together in car
  • Now you will learn how to design the different
    parts of the car
  • NOTE software engineering more complex
  • No physical limitations to abstraction

18
3.2 Designing the Public Interface to a Class
  • Your task Develop a BankAccount class
  • First step Define essential features
  • Behavior of bank account (abstraction)
  • deposit money
  • withdraw money
  • get balance

19
Designing a Class
  • Remember you are designing a class that another
    programmer could use.
  • Design your class as a black box

20
Designing 1 Methods
  • Methods of BankAccount class
  • deposit
  • withdraw
  • getBalance
  • Support method calls such as the following
  • harrysChecking.deposit(2000)
  • harrysChecking.withdraw(500)
  • System.out.println(harrysChecking.getBalance())
  • Which methods are accessors? Mutators?

21
Designing Method Definitions
  • COMPONENTS
  • access specifier (Ex. public)
  • return type (Ex. String or void)
  • method name (Ex. deposit)
  • list of parameters (Ex. amount for deposit)
  • method body in braces

22
  • Examples
  • public void deposit(double amount) ...
  • public void withdraw(double amount) ...
  • public double getBalance() ...

23
Syntax 3.1 Method Definition
  • accessSpecifier returnType methodName(parameterTyp
    e parameterName,...)
  • method body
  • Example
  •   public void deposit(double amount) . . .
  • Purpose
  • To define the behavior of a method

24
Designing 2 Constructor
  • A constructor initializes the instance variables
  • Constructor name class name
  • public BankAccount() // body--filled in later

25
Constructors
  • Constructor body is executed when new object is
    created
  • Statements in constructor body will set the
    internal data of the object that is being
    constructed
  • How does the compile know which constructor to
    call?

26
Constructor vs. Method
  • Constructors are a specialization of methods
  • Goal to set the internal data of the object
  • 2 differences
  • All constructors are named after the class
  • Therefore all constructors of a class have the
    same name
  • No return type listed EVER!

27
Syntax 3.2 Constructor Definition
  • accessSpecifier ClassName(parameterType
    parameterName, . . .) constructor body
  • Example
  • public BankAccount(double initialBalance)
  • . . .
  • Purpose
  • To define the behavior of a constructor

28
BankAccount Public Interface
  • The public constructors and methods of a class
    form the public interface of the class.
  • public class BankAccount
  • // private fields--filled in later
  • // Constructorspublic BankAccount() //
    body--filled in later

29
  • public BankAccount(double initialBalance)
  • // body--filled in later
  • // Methods
  • public void deposit(double amount)
  • // body--filled in later
  • public void withdraw(double amount)
  • // body--filled in later
  • public double getBalance()
  • // body--filled in later

30
Syntax 3.3 Class Definition
  • accessSpecifier class ClassName
  • fields
  • constructors
  • methods
  • Example
  • public class BankAccountpublic
    BankAccount(double initialBalance) ...public
    void deposit(double amount) .... . .
  • PurposeTo define a class, its public interface,
    and its implementation details

31
Remember
  • Public methods and constructors provide the
    public interface to a class
  • They are how you interact with the black box
  • Our class is simple, but we can do many things
    with it
  • Notice we havent defined the method body yet,
    but know how we can use it

32
3.3 Commenting the Public Interface
  • Part of creating a well-defined public interface
    is always commenting the class and methods
    behaviors
  • The HTML pages from the API are created from
    special comments in your program called javadoc
    comments
  • Place before the class or method
  • /
  • ..
  • /

33
Javadoc Comments
  • Begin with /
  • Ends with /
  • Put on lines in between as convention, makes it
    easier to read
  • Javadoc tags - _at_ mark is one
  • _at_author, _at_param, _at_return
  • Benefits
  • Online documentation (Assignment 1)
  • Other java documents

34
Javadoc comments
  • First sentence is extracted for HTML page
  • Carefully explain method
  • _at_param for each parameter
  • Omit if no parameters
  • _at_return for the value returned
  • Omit if return type void

35
  • /Withdraws money from the bank account._at_param
    the amount to withdraw
  • /
  • public void withdraw(double amount)//
    implementation filled in later
  •  
  • /Gets the current balance of the bank
    account._at_return the current balance
  • /
  • public double getBalance()// implementation
    filled in later

36
Class Comment
  • /A bank account has a balance that canbe
    changed by deposits and withdrawals.
  • /
  • public class BankAccount. . .

37
Convention
  • Seems repetitive, but is necessary
  • Very helpful if you comment before you code your
    methods
  • Provide documentation comments for
  • every class
  • every method
  •  every parameter
  • every return value.
  • When in doubt comment
  • But make sure comments are concise

38
(No Transcript)
39
(No Transcript)
40
3.4 Instance Fields
  • Remember methods are the public interface of a
    class
  • Instance Fields are part of the internal workings
    - An object stores its data in instance fields
  • Field a technical term for a storage location
    inside a block of memory
  • Instance of a class an object of the class
  • AKA Data Members

41
  • The class declaration specifies the instance
    fieldspublic class BankAccount     private
    double balance ...

42
  • An instance field declaration consists of the
    following parts
  • access specifier (usually private)
  • type of variable (such as double)
  • name of variable (such as balance)
  • Each object of a class has its own set of
    instance fields
  • You should declare all instance fields as private

43
Access Specifiers
  • Access Specifiers defines the accessibility of
    the instance field and methods
  • private only accessible within the class
    methods
  • public accessible in outside class methods and
    inside class methods
  • Private enforces encapsulation/black box
  • AKA Visibility Modifier

44
(No Transcript)
45
 Syntax 3.4 Instance Field Declaration
  • accessSpecifier class ClassName
  • . . .
  • accessSpecifier fieldType fieldName. . .
  • Example
  • public class BankAccount . . . private
    double balance . . .
  • Purpose To define a field that is present in
    every object of a class

46
Accessing Instance Fields
  • The deposit method of the BankAccount class can
    access the private instance field
  • public void deposit(double amount)   double
    newBalance balance amount   balance
    newBalance

47
  • Other methods cannot
  • public class BankRobber   public static void
    main(String args)        BankAccount
    momsSavings new BankAccount(1000)     . .
    .     momsSavings.balance -1000 // ERROR 
     

48
  • Encapsulation Hiding data and providing access
    through methods
  • By making data members private, we hide internal
    workings of a class from a user
  • Note We can have public instance fields and
    private methods, but commonly we do not

49
3.5 Implementing Constructors Methods
  • Constructors contain instructions to initialize
    the instance fields of an object public
    BankAccount() balance 0public
    BankAccount(double initialBalance) balance
    initialBalance

50
Constructor Call Example
  • BankAccount harrysChecking new
    BankAccount(1000)
  • Create a new object of type BankAccount
  • Call the second constructor (since a construction
    parameter is supplied)
  • Set the parameter variable initialBalance to 1000
  • Set the balance instance field of the newly
    created object to initialBalance
  • Return an object reference, that is, the memory
    location of the object, as the value of the new
    expression
  • Store that object reference in the harrysChecking
    variable

51
Why put instructions in a method?
  • or why not just have one long list of
    instructions in our programs?
  • smaller ?? easier
  • test debug once, execute as often as needed
  • more readable code

52
Method Properties
  • Methods have several components that allow them
    to be functional units of code.

53
Implementing Methods
  • Some methods do not return a value public void
    withdraw(double amount) double newBalance
    balance - amount balance newBalance
  • Some methods return an output value public double
    getBalance() return balance

54
Implementing Methods
  • public void deposit(double amount)
  • double newBalance balance amount
  • balance newBalance

55
Method Call Example
  • harrysChecking.deposit(500)
  • Set the parameter variable amount to 500
  • Fetch the balance field of the object whose
    location is stored in harrysChecking
  • Add the value of amount to balance and store the
    result in the variable newBalance
  • Store the value of newBalance in the balance
    instance field, overwriting the old value

56
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.

57
(No Transcript)
58
(No Transcript)
59
(No Transcript)
60
Wus Template
61
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
62
Defining the class
63
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

Class Name
64
Defining the class
65
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

Declaration (Data Members/Instance Fields
66
Defining the class
67
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 void setExchangeRate (double rate )
  • exchangeRate rate

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

69
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

70
  • / 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
71
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

72
  • / 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 )

73
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

74
  • / 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(

75
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

76
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

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

78
  • 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

79
  • /
  • 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())

80
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)

81
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

82
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

83
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

84
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

85
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

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

87
(No Transcript)
88
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?

89
  • 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

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

91
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)

92
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)

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

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

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

97
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

98
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

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

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

101
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

102
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.)

103
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