Home CPSC 220

Classes & Objects

 

What is an Object?

Object Oriented Programming is a way of designing programs by breaking things down into "objects". Objects combine data members and functions together in one unit. An object consists of three things:

Objects are defined as being part of some class. A class is a blueprint for an object and describes what attributes and behavior it will have. An object is an "instance" of class. There can be many instances of the same class.

Classes are meant to serve as building blocks for use in programs.


 

Using Objects

We have actually used several objects in our programs already:

To use a regular variable, we only need to declare it, and normally initialize it:


int x = 10;     // not an object, so no need for new

To use an object, we need to not only declare it, but also construct it with new:


Scanner in = new Scanner(System.in);    // objects must be constructed

Uninitialized objects are "null" and cannot be used without a NullPointerException

Once we have an object of some class, we can call functions on that object (often called methods). here are the methods of the String class.


 

Creating Our Own Classes

In addition to using built-in classes, we can also create our own. We actually have created a class for each program we have created. In Java, every program needs at least one class with the "main" method, but there can be others as well.

In Java, each code file can contain only one public class, and others must not be public. We can create another class in a file as:


class Name {
    // variables and methods
};

Below is a simple example of a program with a Circle class:


// a class used only in this program
class Circle {
    // a private variable
    private double radius;
    
    // public function to change the radius
    public void setRadius(double r) {
        if (r < 0) {
            throw new IllegalArgumentException("Radius should not be negative");
        }
        radius = r;
    }
    
    // public functions to calculate the area or circumference
    public double getArea() {
        return Math.PI * radius * radius;
    }
    public double getCircumference() {
        return 2.0 * Math.PI * radius;
    }
}

// the "main" class for the program
public class test {
    // the main function
    public static void main(String args[]) {
        // declare two circle objects
        Circle c1, c2;
        
        // construct them
        c1 = new Circle();
        c2 = new Circle();
        
        // set the radii
        c1.setRadius(2.5);
        c2.setRadius(42.0);
        
        // print the information
        System.out.printf("Circle 1: Area = %f, Circumference = %f\n",
            c1.getArea(), c1.getCircumference());
        System.out.printf("Circle 2: Area = %f, Circumference = %f\n",
        c2.getArea(), c2.getCircumference());
    }
}

It is a good idea to keep the data in a class private. That lets us prevent errors such as the code using the class setting the radius to a negative number, for example.


 

static vs. non-static functions

Notice that the functions of the Circle class are not static, unlike the ones we have talked about so far. There is a big difference between static and non-static things in Java:


 

Constructors

In the circle example above, the member data are uninitialized before calling the set functions. If we called getArea before setRadius, what would happen?

In order to avoid this, we need to give the class at least one constructor.

The following two functions are constructors for the Circle class:


    // default constructor sets radius to 0
    public Circle() {
        radius = 0.0;
    }
    
    // constructor which allows a radius to be passed in
    public Circle(double r) {
        setRadius(r);
    }

If we place them in the Circle class (public section), then we can initialize our circles as follows:


    Circle c1 = new Circle();     // default
    Circle c2 = new Circle(42.0);  // non-default

 

this

Notice that the setRadius function takes the parameter as "r" and assigns it to the member variable "radius". What would happen if we use the same name "radius" for each?


// public function to change the radius
public void setRadius(double radius) {
    if (radius < 0) {
        throw new IllegalArgumentException("Radius should not be negative");
    }
    radius = radius;
}

What happens when we run this?

We can avoid this by either using a different name, or by using the "this" keyword which allows us to refer to the member variables unambiguously:


// public function to change the radius
public void setRadius(double radius) {
    if (radius < 0) {
        throw new IllegalArgumentException("Radius should not be negative");
    }
    this.radius = radius;
}

"this" lets you always make sure you refer to the member variables as opposed to a local one.

Copyright © 2024 Ian Finlayson | Licensed under a Attribution-NonCommercial 4.0 International License.