CHAPTER 2 OBJECTS AND CLASSES - PowerPoint PPT Presentation

About This Presentation
Title:

CHAPTER 2 OBJECTS AND CLASSES

Description:

An example: Rectangle Class. Construct a rectangle: new ... Invent a new class, say MoveTest. Supply a main method. Place instructions inside the main method ... – PowerPoint PPT presentation

Number of Views:107
Avg rating:3.0/5.0
Slides: 29
Provided by: jhan6
Learn more at: https://csc.csudh.edu
Category:
Tags: and | chapter | classes | objects

less

Transcript and Presenter's Notes

Title: CHAPTER 2 OBJECTS AND CLASSES


1
CHAPTER 2OBJECTS AND CLASSES
  • Goals
  • To understand the concepts of classes and objects
  • To realize the difference between objects and
    object references
  • 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

2
Objects and Classes
  • Object entity that you can manipulate in your
    programs (by invoking methods)
  • Each object belongs to a class
  • Class Set of objects with the same behavior
  • Class determines legal methods"Hello".println()
    // Error"Hello".length() // OK
  • An example Rectangle Class
  • Construct a rectanglenew Rectangle(5, 10, 20,
    30)new Rectangle()
  • Use the constructed object
  • System.out.println(new Rectangle(5,10,20,30))
  • prints java.awt.Rectanglex5,y10,width20,he
    ight30

3
Rectangle Shapes
A Rectangle Object
4
Syntax 2.1 Object Construction
  • Syntax new ClassName(parameters)
  • Example
  • new Rectangle(5, 10, 20, 30)
  • new Car("BMW 540ti", 2004)
  • Purpose To construct a new object, initialize it
    with the construction parameters, and return a
    reference to the constructed object.
  • Object Variables
  • Declare and optionally initialize
  • Rectangle cerealBox new Rectangle(5, 10, 20,
    30)Rectangle crispyCrunchy
  • Apply methodscerealBox.translate(15, 25)
  • Share objectsr cerealBox

5
Uninitialized and Initialized Variables
Uninitialized
Initialized
Two Object Variables Referring to the Same Object
6
Syntax 2.2 Variable Definition
  • Syntax
  • TypeName variableName
  • TypeName variableName expression
  • Example
  • Rectangle cerealBox
  • String name "Dave"
  • Purpose To define a new variable of a particular
    type and optionally supply an initial value

7
Writing a Test Program
  • Invent a new class, say MoveTest
  • Supply a main method
  • Place instructions inside the main method
  • Import library classes by specifying the package
    and class nameimport java.awt.Rectangle
  • You don't need to import classes in the java.lang
    package such as String and System

Syntax 2.3 Importing a Class from a Package
  • Syntax import packageName.ClassName
  • Example import java.awt.Rectangle
  • Purpose To import a class from a package for use
    in a program

8
File MoveRect.java
  • import java.awt.Rectangle
  • public class MoveTest
  • public static void main(String args)
  • Rectangle cerealBox new Rectangle(5, 10,
    20, 30)
  • // move the rectangle
  • cerealBox.translate(15, 25) // print the
    moved rectangle
  • System.out.println(cerealBox)

public class Greeter public String
sayHello() String message
"Hello,World!" return message
A Simple Class
9
Method Definition
  • Method prototype (signature)
  • access specifier (such as public)
  • return type (such as String or void)
  • method name (such as sayHello)
  • list of parameters (empty for sayHello)
  • Method body in

Example
public class Rectangle . . . public void
translate(int x, int y) method body
. . .
10
Syntax 2.4 Method Implementation
  • Example
  • public class Greeter
  • public String sayHello()
  • String message
  • "Hello,World!" return
    message
  • Purpose To define the behavior of a method A
    method definition specifies the method name,
    parameters, and the statements for carrying out
    the method's actions
  • Syntax
  • public class ClassName
  • ... accessSpecifier returnType
    methodName(parameterType parameterName,...)
    method body
  • ...

11
Syntax 2.5 The return Statement
  • Example
  • return expression
  • or
  • return
  • Example
  • return message
  • 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.

12
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
  • A Test Class for the Greeter Class

public class GreeterTest public static void
main(String args)) Greeter
worldGreeter new Greeter()
System.out.println(worldGreeter.sayHello())

13
Building a Test Program
Testing with the SDK Tools
  • 1. Make a new subfolder for your program.
  • 2. Make two files, one for each class.
  • 3. Compile both files.
  • 4. Run the test program.
  • mkdir greeter
  • cd greeter
  • edit Greeter.java
  • edit GreeterTest.java
  • javac Greeter.java
  • javac GreeterTest.java
  • java GreeterTest

14
Testing with BlueJ
15
Instance Fields
  • public class Greeter
  • ...private String name
  • access specifier (such as private)
  • type of variable (such as String)
  • name of variable (such as name)

Accessing Instance Fields
  • The sayHello method of the Greeter class can
    access the private instance field, others can not
  • public String sayHello() String message
    "Hello, " name "!" return message

16
Syntax 2.6 Instance Field Declaration
  • Syntax
  • accessSpecifier class ClassName ...
    accessSpecifier fieldType fieldName ...
  • Example
  • public class Greeter ... private
    String name ...
  • Purpose To define a field that is present in
    every object of a class

17
Constructors
Syntax 2.7 Constructor Implementation
  • A constructor initializes the instance variables
  • Constructor name class name
  • Invoked in new expressionnew Greeter("Dave")
  • Syntax
  • accessSpecifier class ClassName ...
    accessSpecifier
  • ClassName(parameterType
  • parameterName ...) constructor
    implementation ...
  • Example
  • public class Greeter ... public
    Greeter(String aName) name aName
    ...
  • Purpose To define the behavior of a constructor,
    which is used to initialize the instance fields
    of newly created objects

18
File Greeter.java
File GreeterTest.java
1 public class GreeterTest 2 3 public static
void main(String args) 4 5
Greeter worldGreeter new Greeter("World") 6
System.out.println( worldGreeter.sayHello())
7 8 Greeter daveGreeter new Greeter("Dave")
9 System.out.println(daveGreeter. sayHello())
10 11
  • 1 public class Greeter
  • 2
  • 3 public Greeter(String aName)
  • 4
  • 5 name aName
  • 6
  • 7
  • 8 public String sayHello()
  • 9
  • 10 String message "Hello, "
  • name "!"
  • 11 return message
  • 12
  • 13
  • 14 private String name
  • 15

19
Designing A Class Bank Account
  • Designing Interface
  • Constructor
  • public BankAccount()
  • public BankAccount(double initialBalance)
  • Methods
  • public void deposit(double amount)
  • public void withdraw(double amount)
  • public double getBalance()
  • Analysis
  • Behavior of bank account
  • deposit money
  • withdraw money
  • get balance
  • Methods of BankAccount class
  • deposit
  • withdraw
  • getBalance

20
Commenting
Commenting interface
/ Gets the current balance of the bank
account. _at_return the current balance / public
double getBalance() implementation filled in
later
/ Withdraws money from the bank account.
_at_param the amount to withdraw / public void
withdraw(double amount) implementation
filled in later
  • / A bank account has a balance that can be
    changed by deposits and withdrawals.
  • /
  • public class BankAccount

Commenting the class
21
Javadoc Method Summary
22
Javadoc Method Detail
23
BankAccount Class Implementation
Using the Interface
  • Add interest
  • double rate 5 // 5
  • double amt
  • acct.getBalance() rate / 100
  • acct.deposit(amt)
  • Transfer balance
  • double amt 500
  • momsSavings.withdraw(amt)
  • harrysChecking.deposit(amt)
  • Determine instance variables to hold object state
  • private double balance
  • Implement methods and constructors

24
File BankAccount.java
/ Deposits money into the bank account.
_at_param amount the amount to deposit / public
void deposit(double amount) double
newBalancebalanceamount balance
newBalance / Withdraws money from the
bank account. _at_param amount the amount to
withdraw / public void withdraw(double amount)
double newBalancebalance-amount balance
newBalance / Gets the current balance.
_at_return the current balance / public double
getBalance() return balance
  • /
  • A bank account has a balance that can be
    changed by deposits and withdrawals.
  • /
  • public class BankAccount
  • // instance field
  • private double balance
  • /
  • Constructs a bank account with a zero
    balance
  • /
  • public BankAccount()
  • balance 0

25
File BankAccountTest.java
  • 1 /
  • 2 A class to test the BankAccount class.
  • 3 /
  • 4 public class BankAccountTest
  • 5
  • 6 /
  • 7 Tests the methods of the BankAccount class.
  • 8 _at_param args not used
  • 9 /
  • 10 public static void main(String args)
  • 11
  • 12 BankAccount harrysChecking new
    BankAccount()
  • 13 harrysChecking.deposit(2000)
  • 14 harrysChecking.withdraw(500)
  • 15 System.out.println(harrysChecking.getBalance(
    ))
  • 16
  • 17

26
Calling a Method in BlueJ
27
The Method Return Value in BlueJ
28
Variable Types
  • Instance fields (balance in BankAccount)
  • Local variables (newBalance in deposit method)
  • Parameter variables (amount in deposit method)

Explicit and Implicit Parameters
  • public void withdraw(double amount) double
    newBalance balance - amount balance
    newBalance
  • balance is the balance of the object to the left
    of the dotbalance is an implicit parameter,
    while amount is an explicit parameter
  • momsSavings.withdraw(500)
  • means
  • double newBalance momsSavings.balance -
    amount momsSavings.balance newBalance
Write a Comment
User Comments (0)
About PowerShow.com