Site Navigation

Site Search

Chapter 3: A First Look at Classes and Objects

Learning Objectives

After completion of this chapter, you should be able to

Define Java Classes as blueprints for objects

car class

Java, as an object-oriented programming language, is organized around classes. Programmers write classes and use them to declare objects.

A class definition needs to define both

For example, consider the class used to define a Car

Declare Java objects

Now, consider the object myCar

Declaring Object Reference Variables

A class is the type (blueprint) for an object. It is the model, pattern, or template from which objects are created.

A Car class can be used to define new Car objects

// Declare an object reference variable
   Car myCar;

// Create (instantiate) the actual object
   myCar = new Car("Suburu", "Red", 100232);

// Declare another object reference variable
   Car yourCar;

// Create (instantiate) the actual object
   yourCar = new Car("Ford", "Tan", 55230);

 
  myCar.rePaint("Blue");
  yourCar.rePaint("Green");

object (5K)

Each object is independent of the others. In this example, myCar is independent from yourCar, even though both share a common set of attributes and behaviors.

myCar is called a reference variable because it references the object myCar in memory.

Define a class type: Car

public class Car
{
// Instance Variables
   private String manufacturer;
   private String color;
   private int odometerReading;
     
// Constructor method
   public Car (String m, String c, int odometer)
   {
      manufacturer = m;
      color = c;
      odometerReading = odometer;
   }
     
// Change the Car's color
   public void rePaint(String newColor)
   {
      color = newColor;
   }
   
// Returns the Car's current color
   public String getColor()
   {
      return color;
   }
}

Define and use a new class type: Student

student class diagram

There is no built-in class type in Java to represent a student so let us define a new class to hold information about a student

Declaring Student object reference variables

A main program that uses the Student class to define new Student objects (reference variables)

public class Cs110
{
   public static void main (String[] args)
   {  
   // Declare object reference variables for two students
      Student student1;
      Student student2;
     
   // Create (instantiate) the actual objects
      student1 = new Student("John Smith", 100232);
      student2 = new Student("Jane Doe", 1122334);
     
   // Call some methods  
      student1.setMajor("Computer Science");
      student2.addCourse("Cs110");
   }
}

This class file is saved as Cs110.java

Define the Student class

   public class Student
   {
   // Instance Variables
      private String fullName;
      private int studentId;
      private String major;
      private double gpa;
      private String coursesTaken;
     
   // more to follow

The other two types of access modifiers are public and protected.

This class file is saved as Student.java

Define class methods for Student

We can come up with lots of operations that will apply to students. For example:

To change a student's major, we need to know the name of the new major

   // Change a student's major
      public void setMajor(String newMajor)
      {
         major = newMajor;
      }

newMajor is a parameter whose value is passed into the method. So in the example in Cs110.java,

      student1.setMajor("Computer Science");

newMajor becomes "Computer Science" inside the method setMajor inside Student.java

Write accessor and mutator methods

Two common types of methods written for classes are referred to as accessor (or getter) methods and mutator (or setter) methods

   // Returns the student's full name
      public String getName()
      {
         return fullName;
      }
   
   // Set the student's name
      public void setName(String name)
      {
         fullName = name;
      }

Write a constructor Method

When an object is first created (instantiated), its instance variables are initialized by the class constructor method.

A constructor method looks like an instance method, except that it has no result type and its name is the same as the name of the class itself.

   // Constructor method
      public Student(String name, int id)
      {
         fullName = name;
         studentId = id;
         major = "undeclared";
         gpa = 0.0;
         coursesTaken = "";  
      }

Putting it all together in a class definition for Student

In the real world, we write Java classes for others to use, so we generally add lots of Java documentation comments.

With CS 110 assignments, you are not required to add so many Java documentation comments, instead follow the CS 110 Style Guide

/**
 * Student class.
 */

   public class Student
   {
   // Instance Variables
      private String fullName;
      private int studentId;
      private String major;
      private double gpa;
      private String coursesTaken;
   
   /**
    * Constructor method.
    * Create a new student with a name and ID
    * @param name The student's full name
    * @param id The student's ID
    */

      public Student(String name, int id)
      {
         fullName = name;
         studentId = id;
         major = "undeclared";
         gpa = 0.0;
         coursesTaken = "";  
      }
     
   /**
    * Change a student's major.
    * @param newMajor The student's new major
    */

      public void setMajor(String newMajor)
      {
         major = newMajor;
      }
     
   /**
    * Returns the student's full name.
    * @return The student's full name
    */

      public String getName()
      {
         return fullName;
      }
   
   /**
    * Set the student's name.
    * @param name The student's full name
    */

      public void setName(String name)
      {
         fullName = name;
      }
     
   /**
    * Returns the student's ID.
    * @return The student's ID
    */

      public int getId()
      {
         return studentId;
      }
   
   /**
    * Adds a course to the list of courses taken.
    * @param course The course to be added
    */

      public void addCourse(String course) {
         coursesTaken += " " + course;
      }
     
   /**
    * Returns the list of courses taken by student.
    * @return The courses taken by the student
    */

      public String getCoursesTaken() {
         return coursesTaken;
      }
   }

Generating Java documentation from JavaDoc comments is done using jGRASP's file menu.

Example 2: Develop and use a new class type: the Fraction class

While Java supports double types, it has no built-in support for a fraction type (for example, the fraction 3/8)

Suppose we wanted to write a program that works with fractions (numerator/denominator)

If we define a Fraction class to represent fractional number objects, we could use it in a Java program to work with the new fraction type

   // Declare three fraction object reference variables
      Fraction number1;
      Fraction number2;
     
   // Create (instantiate) the actual objects
      number1 = new Fraction(2, 8);
      number2 = new Fraction(3, 8);
     

Note: number1 and number2 are independent objects of type Fraction. They belong to the same type, but their values are different.

Define the Fraction class

 public class Fraction
 {  
 // Declare the instance variables
    private int numerator;
    private int denominator;
   
 //more to follow

The other two types of access modifiers are public and protected.

Write a Fraction constructor method

When an object is first created (instantiated), its instance variables are initialized by the class constructor method.

A constructor method looks like an instance method, except that it has no result type and its name is the same as the name of the class itself.

   // Constructor method
      public Fraction (int n, int d)
      {
         numerator = n;
         denominator = d;
      }

Write accessor and mutator methods

Two common types of methods written for classes are referred to as accessor (or getter) methods and mutator (or setter) methods

Java programmers use the convention of naming their getter methods as getFieldName and their setter methods as setFieldName. In most cases, setter and getter methods are written for all instance variables.

   // Get the fraction's numerator
      public int getNumerator()
      {
         return numerator;
      }
   
   // Set the fraction's numerator
      public void setNumerator(int n)
      {
         numerator = n;
      }

Define Fraction class methods

We can come up with lots of operations that will apply to fractions. For example:

Write a reciprocal method

   // Takes a Fraction's reciprocal
      public void reciprocal( )
      {
      // Declare a local variables
         int temp;   // old numerator
     
      // Swap the two values
         temp = getNumerator();
         numerator = getDenominator();
         denominator = temp;
      }

Using the Fraction class to create objects in a Java program

    public class FractionTester
   {
       public static void main(String[] args)
      {
      // Declare object reference variables
         Fraction number1;
         Fraction number2;
     
      // Instantiate the first fraction to 4/3
         number1 = new Fraction(4, 3);
         
      // Instantiate the number2 fraction to 2/4
         number2 = new Fraction(2, 4);
     
      // Display the first fraction
         System.out.print(number1.getNumerator());
         System.out.print("/");
         System.out.println(number1.getDenominator());
       
      // Take the reciprocal of the first fraction
         number1.reciprocal();
     
      // Display the reciprocal
         System.out.print(number1.getNumerator());
         System.out.print("/");
         System.out.println(number1.getDenominator());
         
      // Set the number2 fraction to 5/6
         number2.setNumerator(5);
         number2.setDenominator(6);
      }
   }