1 of 24

Classes and Objects

Adapted from

Java Software Solutions

for AP* Computer Science A

2nd Edition

by John Lewis, William Loftus, and Cara Cocking

Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2006 by John Lewis, William Loftus, and Cara Cocking. All rights reserved.

Instructors using the textbook may use and modify these slides for pedagogical purposes.

*AP is a registered trademark of The College Entrance Examination Board which was not involved in the production of, and does not endorse, this product.

1

2 of 24

Writing Classes

  • Focuses on:
    • class definitions
    • encapsulation and Java modifiers
    • Java compiler and JVM

2

3 of 24

Objects

  • An object has:
    • state - descriptive characteristics
    • behaviors - what it can do (or what can be done to it)
  • The state of the coin is its current face (heads or tails)
  • The behavior of the coin is that it can be flipped
  • Note that the behavior of the coin might change its state

3

4 of 24

Classes

  • A class is a blueprint of an object
  • It is the model or pattern from which objects are created
  • For example, the String class is used to define String objects
  • Each String object contains specific characters (its state)
  • Each String object can perform services (behaviors) such as toUpperCase()

4

5 of 24

Classes

  • The String class was provided for us by the Java standard class library
  • But we can also write our own classes that define specific objects that we need
  • For example, suppose we want to write a program that simulates the flipping of a coin
    • We can write a Coin class to represent a coin object

5

6 of 24

Classes

  • The Java language requires that the code for each public class must be stored in its own text file.
  • The filename of the text file that contains a public class must have the same name (case-sensitively) as the class, and must have the file extension ".java"
  • Java requires that every method definition must appear within a class definition

ie. public class Coin needs to be save to a file called Coin.java

6

7 of 24

Java Compiler and JVM

  • 2 Stages
    1. each program file (.java) that contains a class definition is converted by a process called compilation into a sequence of byte codes (.class)
    2. the computer on which the program is being executed carries out the actions of the byte codes.
      • Java Virtual Machine resides on target computer

7

8 of 24

Errors && Exceptions

  • Compile Time Error
    • Syntax Error
    • Program Structure Error
      • ie. no return statement
    • Data Type Error
      • ie. assigning an int to a String
  • Run -Time Error (Exceptions)
    • ArithmeticException
    • ArrayIndexOutOfBoundsException
    • ClassCastException
    • NullPointerException
  • Logical Error

8

9 of 24

Garbage Collection

  • Java virtual machine periodically recycles memory
  • This recycling process is called garbage collection.
  • Virtual machine inspects each value and determines whether the value is still needed by the program.
  • Virtual machine reclaims the memory for later reuse.

9

10 of 24

Classes

  • A class contains data declarations and method declarations

10

int x, y;

char ch;

Data declarations

Method declarations

public class Coins {

11 of 24

Data Scope

  • The scope of data is the area in a program in which that data can be used (referenced)
  • Data declared at the class level can be used by all methods in that class
  • Data declared within a method can be used only in that method
  • Data declared within a method is called local data
  • Scope is defined within { }

11

12 of 24

Instance Data

  • The face variable in the Coin class is called instance data because each instance (object) of the Coin class has its own
  • A class declares the type of the data, but it does not reserve any memory space for it
  • Every time a Coin object is created, a new face variable is created as well
  • The objects of a class share the method definitions, but each has its own data space
  • That's the only way two objects can have different states

12

13 of 24

Constructors Revisited

  • Recall that a constructor is a special method that is used to initialize a newly created object
  • When writing a constructor, remember that:
    • it has the same name as the class
    • it does not return a value
    • it has no return type, not even void
    • it typically sets the initial values of instance variables
  • The programmer does not have to define a constructor for a class
    • All classes have a default constructor implied

14 of 24

Class Design

public class Person

{

private double myHeight;

private double myWeight;

private String myHair;

public Person( double height, double weight, String hair )

{

myHeight = height;

myWeight = weight;

myHair = hair;

}

// ...

}

14

Class Header

Instance Variables

Constructor

Initialize Instance Variables

complete Person Class Ex. 94 [slide 5], 96, 97

15 of 24

Local Data

  • Local variables can be declared inside a method
  • The formal parameters of a method create automatic local variables when the method is invoked
  • When the method finishes, all local variables are destroyed (including the formal parameters)
  • Keep in mind that instance variables, declared at the class level, exists as long as the object exists
  • Any method in the class can refer to instance data

15

16 of 24

Method Decomposition

  • A method should be relatively small, so that it can be understood as a single entity
  • A potentially large method should be decomposed into several smaller methods as needed for clarity
  • A service method of an object may call one or more support methods or helper methods to accomplish its goal
  • Support methods could call other support methods if appropriate

16

17 of 24

Encapsulation

  • We can take one of two views of an object:
    • internal - the variables the object holds and the methods that make the object useful
    • external - the services that an object provides and how the object interacts
  • From the external view, an object is an encapsulated entity, providing a set of specific services
  • These services define the interface to the object
  • Recall that an object is an abstraction, hiding details from the rest of the system

17

18 of 24

Encapsulation

  • An object should be self-governing
  • Any changes to the object's state (its variables) should be made only by that object's methods
  • We should make it difficult, if not impossible, to access an object’s variables other than via its methods
  • The user, or client, of an object can request its services, but it should not have to be aware of how those services are accomplished

18

19 of 24

Encapsulation

  • An encapsulated object can be thought of as a black box
  • Its inner workings are hidden to the client, which invokes only the interface methods

19

Client

Methods

Data

20 of 24

Visibility Modifiers

  • In Java, we accomplish encapsulation through the appropriate use of visibility modifiers
  • A modifier is a Java reserved word that specifies particular characteristics of a method or data value
  • We've used the modifier final to define a constant
  • We will study two visibility modifiers: public and private

20

21 of 24

Visibility Modifiers

  • Members of a class that are declared with public visibility can be accessed from anywhere
  • Public variables violate encapsulation
  • Members of a class that are declared with private visibility can only be accessed from inside the class
  • Members declared without a visibility modifier have default visibility and can be accessed by any class in the same package

21

22 of 24

Visibility Modifiers

  • Methods that provide the object's services are usually declared with public visibility so that they can be invoked by clients
  • Public methods are also called service methods
  • A method created simply to assist a service method is called a support method
  • Since a support method is not intended to be called by a client, it should not be declared with public visibility

22

23 of 24

Preconditions and Postconditions

  • A precondition is a condition that should be true when a method is called

  • A postcondition is a condition that should be true when a method finishes executing

  • These conditions are expressed in comments above the method header

  • Both preconditions and postconditions are a kind of assertion, a logical statement that can be true or false which represents a programmer´s assumptions about a program

23

24 of 24

Other Resources

"Difference between Abstraction and Encapsulation in Java - OOPS." Java67 Java Programming tutorials and Interview Questions.

<http://www.java67.com/2012/08/difference-between-abstraction-and-encapsulation-java-oops.html>

24