1 of 44

Chapter 3: Using Methods, Classes, and Objects

Chapter 3, Barron’s Text 2022-23

2 of 44

Overview

  • Mostly review of CS 11 and CS 12 with some new stuff
  • Writing Methods
  • Objects vs Classes
  • Types of Methods
  • Static vs non-static
  • Access specifers: public, private
  • Other specifiers: static, final
  • Scope
  • References

2

3 of 44

Method Calls and Placement

  • Method
    • A program module
    • Contains a series of statements
    • Carries out a task
  • Execute a method
    • Invoke or call from another method
  • Calling method (client method)
    • Makes a method call
  • Called method
    • Invoked by a calling method
  • Main() method executes automatically
  • Other methods are called as needed

3

3

4 of 44

Method Calls and Placement

4

4

Figure 3-2 The First class with a call to the nameAndAddress()method

5 of 44

Method Calls and Placement

5

Figure 3-3 Placement of methods within a class

5

6 of 44

How to Define a Method

A method must include:

  1. Method header
      • Also called a declaration

2. Method body

      • Between a pair of curly braces
      • Contains the statements that carry out the work
      • Also called implementation

6

6

7 of 44

How to Define a Method

Place the entire method within the class that will use it, not within any other method

7

7

8 of 44

Access Specifiers

  • Also called access modifiers
  • Set the scope or visibility of a variable, method, or class

8

8

9 of 44

Where to Put Specifiers or Modifiers

Static is a non-access modifier. As are final, abstract etc.

9

9

10 of 44

Return Type

  • Describes the type of data the method sends back to the calling method
  • If no data is returned to the method, the return value is void

10

10

11 of 44

Method Name

  • Can be any legal identifier, same rules and conventions as naming variables
    • Must be one word
    • No embedded spaces
    • Cannot be a Java keyword

11

11

12 of 44

Parentheses

  • Every method header contains a set of parentheses that follow the identifier
  • May contain data to be sent to the method called the parameter list

12

12

13 of 44

Parameter List

  • Formal Parameters (aka parameters)
    • the variables defined in the method header
  • Actual Parameters (aka arguments)
    • The current value of the actual parameter is copied into the formal parameter via a method call
    • Ex foo(10); // 10 is an actual parameter
  • Implementation hiding
    • Encapsulation of method details within a class
    • The calling method needs to understand only the interface to the called method
    • Interface
      • The only part of a method that the client sees or with which it interacts (aka the method header)

13

13

14 of 44

Create a method with a single parameter:

  • Define the following:
    • Optional access specifiers
    • Return type for the method
    • Method name
    • Parameter type
    • Local name for the parameter

14

14

15 of 44

Create a method with a single parameter:

15

15

16 of 44

Scope

  • Scope: where a variable or method is visible or accessible
  • Variable scope begins where a variable is declared and end at the } of the body in which it’s declared
  • Instance Variables, static variables, and methods have the scope of the entire class
  • Variables in the formal parameters are local to the method
    • Known only within the boundaries of the method
    • Each time the method executes:
      • The variable is redeclared
      • A new memory location large enough to hold the type is set up and named

16

16

17 of 44

Create a method with multiple parameters:

  • A method can require more than one parameter
  • List the arguments within the call to the method
    • Separate with commas
  • Call a method
    • Arguments sent to the method must match the parameters listed in the method declaration by:
      • Number
      • Type

17

17

18 of 44

Create a method with multiple parameters:

18

19 of 44

Create a method that returns a value:

  • return statement
    • Causes a value to be sent from the called method back to the calling method
  • The return type can be any type used in Java
    • Primitive types
    • Class types
    • void
      • Returns nothing
  • Method type
    • A method’s return type

19

19

20 of 44

return Ends a Method

  • return statement ends a method
    • return value; // for a method with a return type
    • return; // for a method with void return type
  • Unreachable statements
    • Logical flow leaves the method at the return statement
    • Can never execute any code after a return statement
      • Causes a unreachable code compiler error

20

20

21 of 44

Methods Calling Methods

  • Any method might call any number of other methods
  • Method acts as a black box
    • Do not need to know how it works
    • Just call and use the result

21

21

22 of 44

Overloading Methods

  • when two or more methods have the same name
    • but different parameter lists
    • return type is irrelevant
  • the compiler figures out which method to call by matching the method “signature”
    • signature: the method name and parameter list

22

Overloaded Methods

Signature

public int product(int n) {return n*n;}

public double product(double x) {return x*x;}

public double product(double x, double y) {

return x*x;

}

product(int)

product(double) product(double, double)

product(int, double)

product(double, int)

23 of 44

Objects vs Classes

  • Every object is a member of a class
  • Instantiation
    • Shark is an instantiation of the Fish class

Fish shark = new Fish();

  • Is-a relationships
    • An object “is a” concrete example of the class
    • shark “is a” Fish
  • Should be written to support reusability
  • Class client or class user
    • An application or a class that instantiates objects of another prewritten class

23

23

24 of 44

How to Define a Class

  • Assign a name to the class
  • Determine what data and methods will be part of the class
  • Create a class header with three parts:
    • An optional access modifier
    • The keyword class
    • Any legal identifier for the name of the class
  • public class
    • Accessible by all objects

24

24

25 of 44

Class Variables

  • Data fields
    • Variables declared within a class but outside of any method
  • Instance variables
    • Non-static fields given to each object
  • Private access for fields
    • No other classes can access the field’s values
    • Only methods of the same class are allowed to use private variables
    • Information hiding (encapsulation)
  • static variables
    • Typically declare non-static data fields
    • static class variables are not instance variables

25

25

26 of 44

Static vs Non-static Variables

26

Static Variables

Non-static (Instance) Variables

accessed using class name

ex. Math.PI

accessed using instance of a class

ex. String s = “foo”;

SOP(s.length);

can be accessed by static and non static methods

cannot be accessed inside a static method.

shared among all instances of a class.

are specific to that instance of a class.

When you create a class with a static field and instantiate 100 objects, only one copy of that field exists in memory

When you create a class with a nonstatic field and instantiate 100 objects, then 100 copies of that field exist in memory.

  • static is a non-access modifier

27 of 44

Static vs Non-static Methods

27

Static Methods

Non-static (Instance) Methods

also called class methods

also called instance methods

When you use a static field or method, you do not use an object; for example: JOptionPane.showDialog();

Math.pow(3,4);

When you use a nonstatic field or method, you must use an object; for example: System.out.println();

String s = “horse”;

SOP(s.toLowerCase());

When you create a static method in a class and instantiate 100 objects, only one copy of the method exists in memory and the method does not receive a this reference.

When you create a nonstatic method in a class and instantiate 100 objects, only one copy of the method exists in memory, but the method receives a this reference that contains the address of the object currently using it

  • static is a non-access modifier

28 of 44

final keyword

28

  • final is a non-access modifier
  • naming conventions for final variables all caps

final boolean ARE_HORSES_COOL = true;

29 of 44

this keyword

this refers to the current object

Can be used

  1. to refer current class instance variable

Most common usage

  • to invoke current class method
  • to invoke current class constructor

Call to this() must be the first statement in constructor.

  • to pass as an argument in the method

29

class Foo{

int a;

int b;

Foo() { System.out.println(“Foo!”); }

Foo (int x) {

this(); // 3

System.out.println(x);

}

String toString(){

return this.a + “ ” + this.b; // 1

void moo(){

System.out.println(this); // 4

}

void spoo() {

this.moo(); // 2

}

}

30 of 44

this keyword

5. can be used to pass as argument in the constructor call useful if we have to use one object in multiple classes

6. can be used to return current class instance

30

class B{

A obj;

B(A obj){

this.obj = obj;

}

void display(){

System.out.println(obj.data);

}

}

class A{

int data=10;

A(){

B b = new B(this);

b.display();

}

public static void main(String args[]){

A a = new A();

}

}

class C{

C getC(){

return this;

}

void msg(){

System.out.println("Hello java");

}

}

class Test1{

public static void main(String args[]){

new A().getA().msg();

}

}

31 of 44

Class Methods

  • Classes contain methods
    • Mutator (set) methods
      • Set or change field values
    • Accessor (get) methods
      • Retrieve values
    • Non-static (instance) methods
      • “Belong” to objects

31

31

32 of 44

Legal and Illegal Method Calls

32

32

33 of 44

Organizing Classes

class Foo {

// instance variables

// static variables

// constructors

// accessors and mutators

// additional methods

} // Foo

  • A template to organize your classes:

33

33

34 of 44

How to Declare an Object

  • Declaring a class does not create any actual objects
  • To create an instance of a class:
    • Supply a type and an identifier
    • Allocate computer memory for the object
    • Use the new operator to call the constructor

Employee someEmployee;

someEmployee = new Employee();

or

Employee someEmployee = new Employee();

  • After an object is instantiated, its methods can be accessed using:
    • The object’s identifier
    • A dot
    • A method call

34

34

Ex. someEmployee.getRaise();

35 of 44

References

  • Reference to the object
    • The name for a memory address where the object is held
    • a reference stores the location of the object in RAM

35

Primitive Data Types

Reference Data Types

All built in data types

ex. int, double, float

All objects and arrays

ex. String, Random, int []

int num1 = 5;

int num2 = num1;

num1 = 10;

10

5

num1

num2

Both num1 and num2 have their own memory slots. If one is changed, the other is not affected.

Date d1 = new Date(5, 15, 2012);

Date d2 = d1;

5

5

d1

d2

Both d1 and d2 refer to the same location. If one is changed, the other is affected.

d1 and d2 are aliases

2012

month

day

year

36 of 44

References cont…

  • null reference
    • an uninitialized object

AddressBook ab;

    • to test if an object is null

if (ab == null)

    • any reference can be set to null

ab = null;

    • if you fail to initialize any reference, the compiler will set it to null
    • any method call for an object with a null reference will cause a run-time error called a NullPointerException

36

37 of 44

Passing References as Parameters

  • references of passed objects are passed by value
  • the current value of the actual parameter is copied into the formal parameter
  • when an object is passed to a method, a reference to that object is passed, and the formal parameter and the actual parameter become aliases of each other

main () {

A a1 = new A();

foo(a1);

}

void foo(A obj) {

obj.changeStuff();

}

37

obj and a1 are aliases of each other

changes to obj also affect a1

38 of 44

How to Achieve Encapsulation

  • Data hiding using encapsulation
    • Data fields are usually private
    • The client application accesses them only through public interfaces
  • set method
    • Controls the data values used to set a variable
  • get method
    • Controls how a value is retrieved

38

38

39 of 44

Constructors

Employee chauffeur = new Employee();

    • Actually calls method named Employee()
  • Constructor
    • A method that constructs (creates and initializes) class objects
    • Must have the same name as the class it constructs
    • return type is implied (it returns an object of this class type)
    • usually public, or default

39

39

40 of 44

Default Constructor

  • Require no arguments
  • Created automatically by a Java compiler
      • For any class, whenever you do not write any constructor
  • Should initialize all instance variables, generally:
    • Numeric fields
      • Set to 0 (zero)
    • Character fields
      • Set to Unicode ‘\u0000’
    • Boolean fields
      • Set to false
    • Non-primitive object fields
      • Set to null

40

40

41 of 44

Sample Question 1

Consider the Date class:

Consider the following declarations:

Based on the given information, which of the following statements must be true?

  1. The test (d1 == d2) is true
  2. The test (d1 == d2) will cause a compile-time error
  3. The test if (d1.equals(d2)) will cause a compile-time error.
  4. The test if (d1.equals(d2)) is true.
  5. The test if (d1.compareTo(d2) == 0) is true.
  6. The test if (d1.compareTo(d2) == 0) will cause a compile-time error.

Answer: F

The class would need to implement Comparable to have access to compareTo. Note: the AP Exam requires you to know what the compareTo method does, but not how to implement the Comparable interface

41

move this rectangle to see the answer

42 of 44

Sample Question 2

Consider the Card and Deck classes below, which are used to create a Deck of Card objects.

The programmer tests the constructor of the Deck class with the DeckTester class shown below.

When the code is run, a NullPointerException is thrown. Which of the following could be the cause of the error?

  1. The DeckTester class object was not created with new.
  2. In the getCards method, an attempt was made to add a Card to an ArrayList that had not been created with new.
  3. In the getCards method, an attempt was made to construct a Card object without new.

A) I only B) II only C) III only

D) 1 and II only E) II and III only

42

43 of 44

Practice

Do all the questions at the end of Chapter 3 in Barron’s Text

On AP Classroom: covered in Unit 3 Content

43

44 of 44

Sample Question 2 Solution

Answer: B

A NullPointerException is thrown whenever an attempt is made to call a method with an object that hasn’t been created with new. If the ArrayList deck was not created with new, the method call deck.add(someCard) would cause the NullPointerException.

Choice I is incorrect because DeckTester is an objectless class with a static main method, used to test objects in the program.

Choice III is wrong. No methods are called with a null Card object. If an attempt is made to add a Card to a deck without using the key word new, the compiler will find the error before the program is run.

44

Move this box to see answer.