logo

APSU Notes


Classes and Methods - Review

Savitch 5.1-5.3, 6.1-6.4

Topics

5.1 – Class and Method Definitions

Class and Method Definitions

  • Objects in a program can represent real-world objects or abstract concepts.
  • Every object is an instance of a class.
  • A class specifies the attributes of an object and the actions an object can take.
  • A UML class diagram can be used to summarize the properties of a class.

UML class diagram of an Automobile

Instance Variables

  • An instance variable represents an attribute of an object.

    1
    2
    3
    4
    5
    6
    
    public class Dog
    {
      public String name;
      public String breed;
      public int age;
    }
    
  • An instance variable can be accessed outside of the class using the . operator.

    1
    2
    3
    4
    
    Dog myDog = new Dog();
    myDog.name = "Cheetah";
    myDog.breed = "Australian Cattle Dog";
    System.out.println(myDog.name + " is an " + myDog.breed);
    

Methods

  • A method defines an action that an object can perform.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    public class Dog
    {
      public void writeOutput()
      {
        System.out.println("Name: " + name);
        System.out.println("Breed: " + breed);
        System.out.println("Age: " + age);
      }
    }
    
  • A method can be called outside of the class using the .operator.

    1
    
    myDog.writeOutput();
    

Defining void Methods

  • A void method is a method that does not return a value.
  • The method header contains the following information:
    • The access modifier: public
    • The return type: void
    • The name of the method: writeOutput
    • The parameter list:()
  • The method body contains a sequence of statements to execute when the method is called, and must be surrounded by { and }.

Defining Methods That Return a Value

  • A method can be defined to return a value.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    public int getAgeInHumanYears() // return type is int
    {
      int humanAge = 0; // local variable
      if (age <= 2)
        humanAge = age * 11;
      else
        humanAge = 22 + ((age  2) * 5);
      return humanAge; // return statement
    }
    
  • When the method is called, the return value should be stored in a variable.

    1
    
    int humanYears = myDog.getAgeInHumanYears();
    

The Keyword this

  • Within a method definition, the keyword this refers to the object that is performing the action specified by the method.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    public void readData()
    {
      Scanner keyboard = new Scanner(System.in);
      System.out.println("Please enter the dog's name:");
      this.name = keyboard.nextLine();
      System.out.println("Please enter the dog's breed:");
      this.breed = keyboard.nextLine();
      System.out.println("Please enter the dog's age:");
      this.age = keyboard.nextInt();
      keyboard.nextLine();
    }
    

Local Variables and Blocks

  • Any variable declared inside of a method body is local to that method and can not be accessed outside of it.
  • Two different local variables declared in different methods can have the same name.
  • Any variable declared inside of a block (in between a { and a }) is local to that block and can not be accessed outside of it.
  • A variable inside of a block and a variable outside a block can have the same name.

Parameters of a Primitive Type

  • Parameters are variables that are defined in a method header and can be used in the method body.

    1
    2
    3
    4
    5
    6
    
    public void initialize(String name, String breed, int age)
    {
      this.name = name;
      this.bread = breed;
      this.age = age;
    }
    
  • For each parameter defined in a method header, an argument must be provided when the method is called.

    1
    
    myDog.initialize("Cheetah", "Australian Cattle Dog", 2);
    

5.2 – Information Hiding and Encapsulation

Information Hiding

  • Information hiding means that a programmer using a method needs to know what the method does, not how it does it.
  • Comments can be used to specify what a method does.
  • A precondition comment states the conditions that must be true before the method is called.
  • A postcondition comment describes all of the effects produced by a method call.

The public and private Modifiers

  • Java uses the access modifiers public and private to specify how a class, method, or instance variable can be accessed.
  • A public method or instance variable is accessible to a method of any other class.
  • A private method or instance variable is only accessible to methods in the same class.
  • Methods and named constants used outside of the class should be public.
  • Instance variables and methods only used inside the class should be private.

Accessor Methods and Mutator Methods

  • An accessor method or getter can be used to access the value of a private instance variable.
  • A mutator method or setter can be used to change the values of private instance variables.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    public class Dog
    {
      // private instance variables
      private String name;
      private String breed;
      private int age;
    
      public String getName() { return name; } // accessor
      public void setName(String newName) { name = newName; } // mutator
    }
    

Methods Calling Methods

  • A method body can contain a call to another method.
  • If the method being called is in the same class, the receiving object does not need to be specified.
1
2
3
4
5
6
7
8
9
10
public void displayMessage()
{
  System.out.println("Hello from displayMessage!");
  displayRestOfMessage(); // same as this.displayRestOfMessage()
}

private void displayRestOfMessage()
{
  System.out.pritnln("Hello from displayRestOfMessage!");
}

Encapsulation

  • Encapsulation means that the details of a class are hidden if they are not necessary to understand how objects of the class are used.
  • The class interface consists of the headers of the public methods and any public named constants in the class.
  • The implementation of a class consists of the instance variables and method definitions in the class.
  • A class is well encapsulated if changes to the implementation can be made without altering the class interface.

5.3 – Objects and References

Variables of a Class Type

  • A variable of a primitive type stores the value of the variable.
  • A variable of a class type stores a reference to an object.

    1
    2
    3
    4
    
    Dog dog1 = new Dog(); // refers to a new Dog object
    Dog dog2 = dog1; // refers to the same Dog object
    dog1.setName("Rowlf");
    System.out.println(dog2.getName()); // outputs Rowlf
    
  • The == operator used on two variables of a class type only returns true if they refer to the same object.

Defining an equals Method for a Class

  • To support testing if two different objects have the same contents, an equals method needs to be defined for the class.

    1
    2
    3
    4
    5
    6
    
    public boolean equals(Dog otherDog)
    {
      return name.equalsIgnoreCase(otherDog.name) &&
             breed.equalsIgnoreCase(otherDog.breed) &&
             age == otherDog.age;
    }
    

Parameters of a Class Type

  • A parameter of a primitive type stores a copy of the argument.
  • A parameter of a class type stores a reference to the argument.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    public void changeValues(int number, Dog dog)
    {
      number = 42;          // changes the parameter
                            // does not change the argument
    
      dog.setName("Astro"); // changes the argument and parameter
    
      dog = new Dog();      // changes the parameter
                            // does not change the argument
    }
    

Chapter 5 Summary

  • Classes have instance variables to store data and method definitions that perform actions.
  • Each class, instance variable, and method definition can be either public or private. Those that are public can be used or accessed anywhere. A private instance variable cannot be accessed by name outside of its class definition. However, it can be used within the definitions of methods in its class. A private method definition cannot be invoked outside of its class definition. However, it can be invoked within the definitions of methods in its class.
  • Instance variables should be private, even though as a result, they cannot be referenced by name except within the definition of a method of the same class.
  • Accessor methods return the value of an instance variable. Mutator methods set the value of one or more instance variables.
  • Every method belongs to some class and is available to objects created from that class.
  • There are two kinds of methods: methods that return a value and void methods, which do not return a value.
  • You can use the invocation of a method that returns a single quantity anyplace that you can use a value of the method’s return type.
  • You follow the invocation of a void method with a semicolon to form a statement that performs an action.
  • The keyword this, when used within a method definition, represents the object that receives the invocation of the method.
  • A local variable is a variable declared within a method definition. The variable does not exist outside of its method.
  • Arguments in a method invocation must match the formal parameters in the method heading with respect to their number, their order, and their data types.
  • The formal parameters of a method behave like local variables. Each is initialized to the value of the corresponding argument when the method is called. This mechanism of substituting arguments for formal parameters is known as the call-by-value mechanism.
  • Methods can have parameters of a primitive type and/or parameters of a class type, but the two types of parameters behave differently. A parameter of a primitive type is initialized to the primitive value of its corresponding argument. A parameter of a class type is initialized to the memory address, or reference, of the corresponding argument object.
  • Any change made to a parameter of a primitive type is not made to the corresponding argument.
  • A parameter of a class type becomes another name for the corresponding argument in a method invocation. Thus, any change that is made to the state of the parameter will be made to the corresponding argument. However, if a parameter is replaced by another object within the method definition, the original argument is not affected.
  • A method definition can include a call to another method that is in either the same class or a different class.
  • A block is a compound statement that declares a local variable.
  • Encapsulation means that data and actions are combined into a single item—a class object—and that the details of the implementation are hidden. Making all instance variables private is part of the encapsulation process.
  • A method’s precondition comment states the conditions that must be true before the method is invoked. Its postcondition comment tells what will be true after the method is executed. That is, the postcondition describes all the effects produced by an invocation of the method if the precondition holds. Preconditions and postconditions are kinds of assertions.
  • The utility program javadoccreates documentation from a class’s comments that are written in a certain form.
  • Class designers use a notation called UML to represent classes.
  • Unit testing is a methodology in which the programmer writes a suite of

    tests to determine if individual units of code are operating properly.

  • The operators = and ==, when used on objects of a class, do not behave the same as they do when used on primitive types.
  • You usually want to provide an equals method for the classes you define.

6.1 – Constructors

Defining Constructors

  • A constructor is a special method that is called whenever the new keyword is used.
  • Constructors are typically used to initialize private instance variables.
  • A constructor that takes no arguments is called a default constructor .
  • If no constructor is defined, Java defines a default constructor that initializes the private instance variables to default values.
  • Multiple constructors can be defined as long as they have a different number of parameters or have parameters with different types.
  • Constructors with parameters must be provided arguments when invoked.

Example: Pet class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Pet
{
  private String name;
  private int age;
  private double weight;

  // default constructor
  public Pet()
  {
    name = "No name yet.";
    age = 0;
    weight = 0;
  }

  // constructor with parameters
  public Pet(String name, int age, double weight)
  {
    this.name = name;
    this.age = age;
    this.weight = weight;
  }
}

// Calls to constructors:
Pet pet = new Pet(); // calls default constructor
Pet myDog = new Pet("Cheetah", 2, 45); // calls 3-parameter
                                       // constructor

Calling Methods from Constructors

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Pet
{
  private String name;
  private int age;
  private double weight;

  public Pet()
  {
    set("No name yet.", 0, 0); // calls private method set
  }

  public Pet(String name, int age, double weight)
  {
    set(name, age, weight); // calls private method set
  }

  public Pet(String name)
  {
    set(name, 0, 0); // calls private method set
  }

  // initializes the private data members
  private void set(String name, int age, double weight)
  {
    this.name = name;
    this.age = age;
    this.weight = weight;
  }

}

6.2 – Static Variables and Static Methods

Static Variables

  • Each object of a class has its own copy of an instance variable.
  • A static variable is a variable that is shared by all objects of a class.
  • Static variables can be declared using the keyword static.

    1
    
    private static int numberOfInvocations;
    
  • Named constants are also declared as static as there is no reason for each object to have its own copy of a constant.
  • To access a public static constant or variable outside of a class, it must be preceded by the class name and the . operator.
  • Example: System.out and System.in are static constants in the classSystem.

Static Methods

  • A static method can be invoked without creating an object.
  • Static methods can be declared using the keywords static.

    1
    
    public static void main (String args[]);
    
  • To access a public static method outside of a class, it must be preceded by the class name and the . operator.

    1
    
    double root =Math.sqrt(2);
    
  • Static methods can only access instance variables and non-static methods if another object of the class has been explicitly created.

The main Method

  • Static methods can be used to divide the main method into subtasks.
  • A main method can also be added to a class to test it.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    class Pet
    {
      public static void main(String [] args)
      {
        pet1 = new Pet("Garfield", 42, 24)
        pet2 = new Pet("Odie", 42, 38);
        runTest(pet1, pet2);
      }
    
      private static void runTest(Pet pet1, Pet pet2) { ... }
    }
    

The Math Class

  • The java Math class contains static methods for several mathematical functions.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    result = Math.pow(x, y) // Computes x^y
    result = Math.abs(x)    // Computes |x|
    result = Math.max(x, y) // Returns the larger of x and y
    result = Math.min(x, y) // Returns the smaller of x and y
    result = Math.random()  // Returns random number between 0 and 1
    result = Math.round(x)  // Rounds x to the nearest integer
    result = Math.ceil(x)   // Rounds x up
    result = Math.floor(x)  // Rounds x down
    result = Math.sqrt(x)   // Computes square root of x
    

Wrapper Classes

  • Java provides wrapper classes for each primitive type that contain methods specific to each type.
1
2
3
4
5
6
7
8
9
10
11
Integer num = new Integer(42); // Integer class constructor

Integer num = 42; // same as above, uses boxing to convert to object

int ival = num.intValue(); // converts back to an int

int ival = num; // same as above, uses unboxing to convert to int

double num = Double.parseDouble("3.14159"); // converts to double

char ch = Character.toUpperCase('a'); // converts to upper case

6.3 – Writing Methods

Decomposition

  • Decomposition is the process of breaking a task into subtasks.
  • Example: display double amount as dollars and cents
    • Set dollars to the number of whole dollars in amount.
    • Set cents to the number of cents in amount, rounded to two decimal places.
    • Display a dollar sign, dollars, and a decimal point.
    • Display cents as a two digit integer.
  • Each task can be solved separately, then converted to code.
  • Solutions to subtasks can be implemented as separate private methods.

Addressing Compiler Concerns

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static int badMax(int val1, int val2)
{
  if (val1 > val2)       // This code will not compile because
    return val1;         // it does not cover the case where
  else if (val2 > val1)  // val1 == val2
    return val2;
}

public static int goodMax(int val1, int val2)
{
  int answer = val1;     // Creating a variable for the return value
  if(val2 > val1)        // and using a single return statement
    answer = val2        // guarantees that a value will be returned
  return answer;
}

The null Constant

  • If a variable of a class type needs to be initialized, the constant null can be used.

    1
    
    String line = null;
    
  • The null constant is a placeholder that does not refer to an actual object.
  • Variables of class type may be compared with null using ==and !=.

    1
    2
    
    if (line == null)
        ...
    
  • If the . operator is used on a variable with a value of null, it will generate a null pointer exception and halt the program.

Testing Methods

  • Every method written for a class should be tested.
  • Methods that test other methods are called drivers .
  • Bottom-up testing requires a method to be tested before any method that calls it.
  • Alternatively, a method can be implemented in a simplified form as a stub so that other methods that call it can be tested.

    1
    2
    3
    4
    
    public static void write(double amount)
    {
      System.out.print("$99.12"); // Stub method
    }
    

6.4 – Overloading

Overloading Basics

  • A method name is overloaded if there are two or more methods in the same class with that name.
  • The signature of a method consists of its name and parameter types.
  • Methods in the same class with the same name must have different signatures.
1
2
3
4
5
6
7
8
9
public double getAverage(double first, double second)
{
  return (first + second) / 2.0;
}

public double getAverage(double first, double second, double third)
{
  return (first + second + third) / 3.0;
}

Overloading and Automatic Type Conversion

  • Automatic type conversion can interfere with overloading.
  • Consider the following overloaded methods:

    1
    2
    
    public static void problemMethod(double n1, int n2) { ... }
    public static void problemMethod(int n1, double n2) { ... }
    
  • These methods are legal, but the following call will generate a compiler error:

    1
    
    problemMethod(5, 10); // could invoke either method
    
  • An int can be automatically converted to a double.
  • The compiler can not determine which method to use.

Overloading and the Return Type

  • The return type of a method is not part of its signature, so two overloaded methods cannot differ only by return type.
  • Consider the following methods:

    1
    2
    
    public double getWeight() { ... }
    public int getWeight() { ... }
    
  • A class with both methods will generate a compiler error since the following statement would be compatible with both methods:

    1
    
    double value =myPet.getWeight();
    

Chapter 6 Summary

  • A constructor is a method that creates and initializes an object of the class when you invoke it using the operator new. A constructor must have the same name as the class.
  • A constructor without parameters is called a default constructor. A class that does not define a constructor will be given a default constructor automatically. A class that defines one or more constructors, none of which is a default constructor, will have no default constructor.
  • When defining a constructor for a class, you can use this as a name for another constructor in the same class. Any call to this must be the first action taken by the constructor.
  • The declaration of a static variable contains the keyword static. A static variable is shared by all the objects of its class.
  • The heading of a static method contains the keyword static. A static method is typically invoked using the class name instead of an object name. A static method cannot reference an instance variable of the class, nor can it invoke a non-static method of the class without using an object of the class.
  • Each primitive type has a wrapper class that serves as a class version of that primitive type. Wrapper classes also contain a number of useful predefined constants and methods.
  • Java performs an automatic type cast from a value of a primitive type to an object of its corresponding wrapper class—and vice versa—whenever it is needed.
  • When writing a method definition, divide the task to be accomplished into subtasks.
  • Every method should be tested in a program in which it is the only untested method.
  • Two or more methods within the same class can have the same name if they have different numbers of parameters or some parameters of differing types. That is, the methods must have different signatures. This is called overloading the method name.
  • An enumeration is actually a class. Thus, you can define instance variables, constructors, and methods within an enumeration.
  • You can form a package of class definitions you use frequently. Each such class must be in its own file within the same folder (directory) and contain a package statement at its beginning.

Powerpoint

Quiz

Quiz 1