Lesson Purpose

Understand how to write classes with attributes and methods (Java OOP)

Hack 1

  • Write the first part of the Cow class, with the body consisting of the instance variables and constructors

  • If the "Output produced" cell is blank, there is no output produced from the code segment

5.1 Anatomy of a Class

Methods

  • Define what an object can do or the behavior of an object
  • Can access and use the object's instance variables ### Main Method
public static void main(String[] args){
    
}
  • String[] args: an array consisting of command-line arguments (Strings)
// Basic Java Class

public class Snack { // class name always starts with capital letter

    /*
     * Instance variables
     * Always declared right after class declaration
     * Declared with TYPE and NAME
     */
    private String name;
    private int calories;

    // constructor
    public Snack(String n, int c){
        name = n;
        calories = c;
    }

    // methods
    public String getName(){ // accessor
        return name;
    }

    public void setName(String n){ // mutator
        name = n;
    }

    // main method
    public static void main(String[] args) {
        Snack one = new Snack("Oreos", 100);
        System.out.println(one.getName());
    }
}

Snack.main(null);
Oreos

Access Modifiers

Data Encapsulation

  • Data can be accessible or modifiable, BOTH, or NEITHER

Read-Only

  • Instance variables are declared with the private keyword ==> outside the class, the instance variables can only be accessed via public methods of the class
public class Cow {

    // instance variables
    private String cowType;
    private String sound;
    private int numMilkings;

    // constructor
    public Cow (String cowType, String sound){
        this.numMilkings = 0;
        this.cowType = cowType;
        this.sound = sound;
    }

    public String getSound(){
        return sound;
    }
}    

public class CowDriver{
    public static void main(String[] args) {
        Cow myCow = new Cow("holstein", "moo");
        System.out.println(myCow.getSound());
        // myCow.sound = "bark!";
    }
}

CowDriver.main(null);
moo
public class Snack {

    private String name;
    private int calories;

    public Snack(String n, int c){
        name = n;
        calories = c;
    }

    public String getName(){ // accessor
        return name;
    }
}

public class SnackDriver {

    public static void main(String[] args) {
        Snack one = new Snack("Oreos", 100);
        System.out.println(one.getName()); // only accessible with getter
        System.out.println(one.name);
    }
}

SnackDriver.main(null);
|           System.out.println(one.name);
name has private access in Snack

Write-Only

public class Snack {

    private String name;
    private int calories;

    public Snack(String n, int c){
        name = n;
        calories = c;
    }

    public void setName(String n){ // accessor
        name = n;
    }
}

public class SnackDriver {

    public static void main(String[] args) {
        Snack one = new Snack("Oreos", 100);
        one.setName("Double Stuffed Oreos"); // only accessible with setter
        one.name = "Golden Oreos";
    }
}

SnackDriver.main(null);
|           one.name = "Golden Oreos";
name has private access in Snack

5.2 Constructors

  • Every instance of the Snack class has the attributes name and calories

public class Snack {

    private String name;
    private int calories;

    /*
     * Constructors
     * Syntax: 
        *  Written after instance variables, before methods
        * Name must match name of the class
        * No return type
     */

    // default constructor
    public Snack(){
        name = null;
        calories = 0;
    }

    // constructor parameters (n and c) are local variables for the constructor only
        // you cannot use n and c anywhere else unless you specify them as parameters for another method
    public Snack(String n, int c){
        name = n;
        calories = c;
    }

    public String getName(){ // accessor
        return name;
    }
    
    public static void main(String[] args) {
        Snack one = new Snack();
        System.out.println("Using Default Constructor: " + one.getName());
        Snack two = new Snack("Oreos", 100);
        System.out.println("Using Two Constructor: " + two.getName());
    }
}

Snack.main(null);
Using Default Constructor: null
Using Two Constructor: Oreos

Hack 2

  • Write a default constructor and all-argument constructor for the Cow class
    • Hint: all-argument constructor should have 3 parameters
  • Create 3 objects, with each object using a different constructor
    • ie object1 uses default constructor, object2 uses constructor with 2 parameters...

5.3 Comments

  • Ignored by compiler, not executed
  • Make code more readable for humans or prevent execution when testing
  • Are NOT required on AP Exam

Types

  • Multi-line comments (/**/)
  • Single-line comments (//)
  • Javadoc comments
    • Javadoc tool that comes with the Java JDK can pull out comments and create a web page with all your comments

Other Vocab

  • Precondition: condition that must be true before execution of a code block
    • Methods don't need to check preconditions
  • Postcondition: condition that is ALWAYS true after the execution of a code block
    • Outcome
    • State of instance variables

5.4 Accessor Method (Getters)

  • Allows other objects outside of the class to obtain values of instance variables or static variables
  • Non-void method returns a single value
    • Header includes return type (String, int, Long etc)
  • "return by value": return expression at the end of a method will specify that value that will be returned (must correspond to the type)
  • Must be used when different classes need to access the instance variables
// always public
// must specify return type
// getVariable (typical naming convention)
// no parameters

public String getVariable(){

}

toString() Method

  • Overridden method that provides description of a specific object (ie values of instance variables)
  • If System.out.print or System.out.println() is passed an object, that object's toString() method is called ==> returned string is printed
    • Java default toString() will return a hashcode, but you can manually write your own toString() method
// method header always stays the same
// always returns string
// no parameters

public String toString(){

}

Example

public class Snack {

    private String name;
    private int calories;

    public Snack(String n, int c){
        name = n;
        calories = c;
    }

    // return values of instance variables
    public String toString(){
        return "Name: " + name + "; " + "Calories: " + calories;
    }
    
    public static void main(String[] args) {
        Snack two = new Snack("Oreos", 100);
        System.out.println(two);
    }
}

Snack.main(null);
Name: Oreos; Calories: 100

5.5 Mutator Method (Modifier/Setter)

  • Typically a void method that changes value of instance variables or static variables
    • void methods do not return values
  • Must be used when different classes need to modify instance variables
// always public void
// setVariable (naming convention)
// parameter type must match type of instance variable being modified

public void setVariable(String variable){
    this.variable = variable;
}

Hack 3

  • Create the toString method for the Cow class
  • Create at least one accessor and one mutator method for the Cow class
  • Call the getter and setter methods for one of your Cow objects

5.6 Writing Methods

Hack 4

  • Add verse three with the rhyme “knee” to The Old Man Song
  • Add verse four with the rhyme "door"
public class Song
{

  /** Verse - prints out a verse of the song
   * @param number - a String like "one", "two", etc.
   * @param rhyme - a String like "thumb", "shoe", etc.
   */
   public void verse(String number, String rhyme)
   {
     System.out.println("This old man, he played " + number);
     System.out.println("He played knick knack on my " + rhyme);
   }

  // The chorus method
  public void chorus()
  {
     System.out.println("With a knick knack paddy whack, give a dog a bone.");
     System.out.println("This old man came rolling home.");
  }

  public static void main(String args[])
  {
      Song mySong = new Song();
      mySong.verse("one", "thumb");
      mySong.chorus();
      mySong.verse("two", "shoe");
      mySong.chorus();
  }
}

Song.main(null);
This old man, he played one
He played knick knack on my thumb
With a knick knack paddy whack, give a dog a bone.
This old man came rolling home.
This old man, he played two
He played knick knack on my shoe
With a knick knack paddy whack, give a dog a bone.
This old man came rolling home.