Writing Classes Notes

Hack 1

  • Write first part of Cow class, with body consisting of instance variables and constructors
public class Cow {
    String sound = "moo";
    String type; 
    int numMilkings;

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

    public String getType() {
        return this.type;
    }

    public int getNumMilkings() {
        return this.numMilkings;
    }

    public String getSound() {
        return this.sound;
    }

    public void milkCow() {
        this.numMilkings++;
    }
}

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

CowDriver.main(null);
holstein

Data Encapsulation

  • Can restruct access to read-only or write-only through accessor/mutator methods

5.4 Accessor Methods (getters)

  • Non-void, includes a return type
  • toString will return a string from an object's properties
public String toString() {
    return "Type: " +  type;
}

5.5 Mutator Method (Setter)

  • Usually a void avriable that changes static variables

Static Variables and Methods

  • Static variables and methods belong to a class and are called with a ClassName rather than the object name

this keyword

  • refers to the instance variables in a class