Part One - What are objects?

In the real world, you'll often find many individual objects all of the same kind. Think about a mug, it is mass produced and there may be many mugs that are similar. Each one of those mugs was mass-produced and was built from the same factory. However that mug may have its own properties for example it may have a different color and size from other mugs. In java we represent a mug with an Object.

The object itself can be looked at as having a state and behaviors. An objects has fieldsthat act as its state and it has methods that act as its behavior. For the example of the coffee mug, it's state may consist of how large it is, what color the mug is and how much liquid it contains. Its behaviors are filling it up, pouring it out and observing the amount of liquid contined, color and size.

The diagram above show how we protect the state of the object, except for the ways that we define to use it. This is called data encapsulation and it's one of the three principles of object-oriented programming.

Part Two - Making our first object

Making the class

Lets make the Mug class and then create a Mug object

// note that Java best practice dictates 
// class names should start with a capital letter
public class Mug {
        
    // the Mug class has three fields
    private String color;
    private int size;
    private int fill;
        
    // the Mug class has one constructor
    public Mug( int startColor, int startSize) {
        color = startColor;
        size = startSize;
        fill = 0;
    }
        
    // the implementation of the getColor method
    public String getColor() {
        return color;
    }
    
    // the implementation of the getSize method
    public String getSize() {
        return size;
    }

    // the getFill 'accessor' or 'getter'
    public String getFill() {
        return fill;
    }
    
    // the Mug class also has methods to fill up and pour out the liquid
    public void fill( int liquidAmount ) {
        fill += liquidAmount;

        if ( fill > size ) {
            fill = size;
        }
    }
        
    public void pour(int liquidAmount) {
        fill -= liquidAmount;

        if ( fill < 0 ) {
            fill = 0;
        }
    }
        
}
      

Making and using the object

Great, we just made our first class. Now lets make our first object. Open up another file in doctor java.

public class MugTest {
  public static void main (String[] args){
    
    Mug myMug = new Mug( "White", 650 );
    myMug.fill( 600 );
    myMug.pour( 250 ); 

    System.out.println( "The mug contains " + myMug.getFill + "ml." );
  }
}
      

Part Three - Fields

Like we said before fields represent the state of an object. Lets make a new field called 'handle' together.

Part Four - Instance methods, getters and setters

In lesson 6 we learned how to make static methods. In this lesson we will make instance methods for our Mug object. Lets make a method to paint the mug as well as a method to observe whether or not the mug has a handle.

the paint method should take an String as an argument and change the color field. the hasHandle() method should return a true or false answer for whether or not the mug has a handle:

Part Five - The Constructor and Overloading

The constructor is what makes an object. I'ts whats called when we use the new keyword.

In the Mug class our constructor looks like this (note that we have changed the constructor to accomodate our new 'handle' field):

public Mug( String startColor, int startSize, boolean hasHandle ) {
    color = startColor;
    size = startSize;
    handle = hasHandle;
    fill = 0;
}
      

Overloading the constructor

What if we dont know all that information? Wouldnt it be helpful to have a default constructor that creates a Mug object without any arguments.

In Java you can just write a second constructor and when the code is compiled Java will figure out which constructor to use, based on what arguments you give it. This is part of what we nerds call Polymorphism. I'ts the second principle of object-oriented programming.

Lets write an overloaded constructor together

Part Six - creating a toString method

It is considered good practice in java to override the toString() method of an object.

A good toString will provide usefull informaton about the object. Once you have a toString method it will automatically be called when you pass the object into System.out.println();

Lets write a good toString method

Part Seven - Using our new fields and methods

Now go back to our MugTest class from before. Lets put these new fields and methods to use!

Use the default constructor this time. Then print the String that toString returns.

Change each of the fields using thier setter methods. Each time print out the toString.

Part Eight - Practice!

Write a class called Animal that has fields for name and sound.

Write two constructors, getters, setters and a toString for this class

Part Nine - Inheritance

Different kinds of objects often have a certain amount in common with each other. Dogs, cats, cows and chickens for example, all share the characteristics of Animal. Yet each also defines additional features that make them different. Dogs and cats for example have tails, chickens have wings and cows can make milk.

The important thing for you to take away from this is that
a Dog IS A Animal
a Cat IS A Animal
a Cow IS A Animal
a Chicken IS A Animal

This brings us to the third and final principle of object-oriented progrraming, inheritance. Cow can inherit some of the properties of Animal and since it IS A Animal a Cow object can be used anywhere a Animal can.

Enough with the conceptual nonsense. Lets write the Cow class.

public class Cow extends Animal {
    /**
     * Cow now inherits all of Animals fields
     * name and sound
     * as well as 
     * setSound(), getSound(), setNoise(), getNoise() and toString()
     *
     * YES... ITS THAT EASY
     */

    // Although we still have to write a constructor for it...
    public Cow ( String newName ) {
        name = newName;
        sound = "moo";
    }

    // now we can add a new method called Milk
    // it will return a number representing the amount of milk the cow gave (in ml)
    public int milk() {
      return (int) Math.floor(Math.random() * 1000);
    }

    // we should also override the toSting method
    public String toString() { 
        return "The cow named "+name+" says "+sound;
    }
}
      

As you can see we have the ability to OVERRIDE (not overload) inherited methods. Lets test out all of the new functionality of our cow and animal classes

Part Eleven - Practice!

Lets write a class called Point and has all of the following...

and of course another class with a main method that tests our point objects

Home Work

1. Write a class Circle which inherits from point that has all of the following.

In case you forgot...

Circumfrence:
C = 2\pi r = \pi d\,

Area:
\mathrm{Area} = \pi r^2.\,

Also write a class with a main method to test all of Circle's methods

2. Write a class called Cylinder that inherits from Circle and adds one new field, height, and three new methods, getHeight, setHeight and getVolume

Volume:

V = Height * Area

Hint: You'll probably need to use Math.pow() and Math.PI

The full documentation on the math class can be found here: java.lang.Math