Title: Writing Classes
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Writing Classes

Writing Functions


import java.util.Scanner;

public class FirstFunctions
{
    static Scanner scan;

    public static double average(double d1, double d2, double d3)
    {
        double retVal = (d1 + d2 + d3)/3.0;

        return retVal;
    }

    public static double getNum(String prompt)
    {
        System.out.println(prompt);
        double retVal = scan.nextDouble();
        return retVal;
    }

    public static void main(String[] args)
    {
        scan = new Scanner(System.in);
        double d1 = getNum("Enter First Number");
        double d2 = getNum("Enter Second Number");
        double d3 = getNum("Enter Third Number");

        double a;
        a = average(d1, d2, d3);
        System.out.println("average = "+ a);

    }
}




Methods:

Often it is useful to break a problem down into smaller well defined problems. A function gives you this capability. To make functions useful we can have:

Method Parameters- A function can have any number of parameters, and the parameters can be of any type. Note the 3 doubles passed in as parameters to the average method.

A single entity can be returned - A primitive or a class object can be returned in a method. Note that the definition of the method declares what is returned. Once declared, the method must have a return statement that returns the specified value.

void return - If a method doesn't return anything then the return type of the method should be declared as void. See the definition of main.

Consider if we want to access static methods and variables in Static classes and we are not inside of the Static class itself. Check out the UsingFirstFunctions class.


import java.util.Scanner;

public class UsingFirstFunctions
{


    public static void main(String[] args)
    {
        FirstFunctions.scan = new Scanner(System.in);
        double d1 = FirstFunctions.getNum("Enter First Number");
        double d2 = FirstFunctions.getNum("Enter Second Number");
        double d3 = FirstFunctions.getNum("Enter Third Number");

        double a;
        a = FirstFunctions.average(d1, d2, d3);
        System.out.println("average = "+ a);

    }
}




static classes & methods versus regular non-static classes & methods

In the previous examples we have been using static methods and classes. Static methods and classes are used to work in a non-object oriented programming approach. Static methods are very comparable to traditional non-object oriented languages like Fortran, C, etc. Actually, static methods are similar to C++ methods if Classes aren't being used.

Objects - The alternative to the static approach is to create objects. Any number of Objects can be created from a defined class.

Here is an example of the a non-static version of the above:


import java.util.Scanner;

public class FirstFunctions
{
    Scanner scan;
	public FirstFunctions()
	{
	    scan = new Scanner(System.in);
	}
    public double average(double d1, double d2, double d3)
    {
        double retVal = (d1 + d2 + d3)/3.0;

        return retVal;
    }

    public double getNum(String prompt)
    {
        System.out.println(prompt);
        double retVal = scan.nextDouble();
        return retVal;
    }

    public static void main(String[] args)
    {
        FirstFunctions ffunct = new FirstFunctions();

        double d1 = ffunct.getNum("Enter First Number");
        double d2 = ffunct.getNum("Enter Second Number");
        double d3 = ffunct.getNum("Enter Third Number");

        double a;
        a = ffunct.average(d1, d2, d3);
        System.out.println("average = "+ a);

    }
}




In the following example, you will see a class called:

Die

To create 2 object instances of Die, you issue the statements:

Die die1 = new Die();

Die die2 = new Die();

The objects die1 and die2 are allocated from a memory area known as the heap which is a globally allocated area of memory for Java.

Die.java


//********************************************************************
//  Die.java       Author: Lewis/Loftus
//
//  Represents one die (singular of dice) with faces showing values
//  between 1 and 6.
//********************************************************************

public class Die
{
   private final int MAX = 6;  // maximum face value

   private int faceValue;  // current value showing on the die

   //-----------------------------------------------------------------
   //  Constructor: Sets the initial face value.
   //-----------------------------------------------------------------
   public Die()
   {
      faceValue = 1;
   }

   //-----------------------------------------------------------------
   //  Rolls the die and returns the result.
   //-----------------------------------------------------------------
   public int roll()
   {
      faceValue = (int)(Math.random() * MAX) + 1;

      return faceValue;
   }

   //-----------------------------------------------------------------
   //  Face value mutator.
   //-----------------------------------------------------------------
   public void setFaceValue (int value)
   {
      faceValue = value;
   }

   //-----------------------------------------------------------------
   //  Face value accessor.
   //-----------------------------------------------------------------
   public int getFaceValue()
   {
      return faceValue;
   }

   //-----------------------------------------------------------------
   //  Returns a string representation of this die.
   //-----------------------------------------------------------------
   public String toString()
   {
      String result = Integer.toString(faceValue);

      return result;
   }
// Note that classes don't need a main if they are never executed directly
// from the command line.  Remove this main to demonstrate that you can
// compile without a main routine.


   public static void main (String[] args)
   {
     // Quick test of class
     Die die1 = new Die();
     System.out.println(" first value of die1 = "+ die1);

     die1.setFaceValue(2);
     System.out.println(" second value of die1 = "+ die1);

	 System.out.println(" Another way to get die1 value = " + die1.getFaceValue());

	 die1.roll();
     System.out.println(" third value of die1 = "+ die1);

   }
}



Some Points on the above example:

The keyword public marks a class and its methods available to everyone. We will discuss this in more detail at some later time.

The keyword private means that a piece of data or a method is only available inside the class itself. There is a strong push for the following class characteristics:

- Data is marked as private.
- All access to this data is provided through public accessor methods like getFaceValue. An accessor method just provides a way for anyone outside of a class to get at a particular value.
- All modification requests are made with public mutator methods like like setFaceValue. A mutator method just provides a way for anyone outside of a class to modify a particular value.

Note that this is not enforced in Java, but it is merely a recommended general approach. The text seems to like using this conventional in all of its examples, however, it will be shown later that other approaches can be taken.

The statement:
public Die()
is a constructor. A constructor is executed when a class object is created. For example, the Die() constructor is called during the following statement:

Die die1 = new Die();

A constructor provides a place where you can initialize data inside of a class like Die. If your class requires no initialization, you can have a class without any constructor. If you don't provide a constructor, the compiler creates a default constructor that doesn't do anything (i.e.):

// Default constructor provided by compiler:
public Die()
{
}

The toString method will be called whenever Java has a need to printout the contents of a Die class such as in the following statement:

System.out.println(" first value of die1 = "+ die1);

The method main is not required to make the Die class into a useful class that can be compiled. However, if you remove the main method, you won't be able to issue the command:

java Die

If you do remove the main method in the Die class, you can still use the Die class in the following example called RollingDice.

RollingDice.java


//********************************************************************
//  RollingDice.java       Author: Lewis/Loftus
//
//  Demonstrates the creation and use of a user-defined class.
//********************************************************************

public class RollingDice
{
   //-----------------------------------------------------------------
   //  Creates two Die objects and rolls them several times.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      Die die1, die2;
      int sum;

      die1 = new Die();
      die2 = new Die();

      die1.roll();
      die2.roll();
      System.out.println ("Die One: " + die1 + ", Die Two: " + die2);

      die1.roll();
      die2.setFaceValue(4);
      System.out.println ("Die One: " + die1 + ", Die Two: " + die2);

      sum = die1.getFaceValue() + die2.getFaceValue();
      System.out.println ("Sum: " + sum);

      sum = die1.roll() + die2.roll();
      System.out.println ("Die One: " + die1 + ", Die Two: " + die2);
      System.out.println ("New sum: " + sum);
   }
}



Account.java


//********************************************************************
//  Account.java       Author: Lewis/Loftus
//
//  Represents a bank account with basic services such as deposit
//  and withdraw.
//********************************************************************

import java.text.NumberFormat;

public class Account
{
   private final double RATE = 0.035;  // interest rate of 3.5%

   private long acctNumber;
   private double balance;
   private String name;

   //-----------------------------------------------------------------
   //  Sets up the account by defining its owner, account number,
   //  and initial balance.
   //-----------------------------------------------------------------
   public Account (String owner, long account, double initial)
   {
      name = owner;
      acctNumber = account;
      balance = initial;
   }

   //-----------------------------------------------------------------
   //  Deposits the specified amount into the account. Returns the
   //  new balance.
   //-----------------------------------------------------------------
   public double deposit (double amount)
   {
      balance = balance + amount;

      return balance;
   }

   //-----------------------------------------------------------------
   //  Withdraws the specified amount from the account and applies
   //  the fee. Returns the new balance.
   //-----------------------------------------------------------------
   public double withdraw (double amount, double fee)
   {
      balance = balance - amount - fee;

      return balance;
   }

   //-----------------------------------------------------------------
   //  Adds interest to the account and returns the new balance.
   //-----------------------------------------------------------------
   public double addInterest ()
   {
      balance += (balance * RATE);
      return balance;
   }

   //-----------------------------------------------------------------
   //  Returns the current balance of the account.
   //-----------------------------------------------------------------
   public double getBalance ()
   {
      return balance;
   }

   //-----------------------------------------------------------------
   //  Returns a one-line description of the account as a string.
   //-----------------------------------------------------------------
   public String toString ()
   {
      NumberFormat fmt = NumberFormat.getCurrencyInstance();

      return (acctNumber + "\t" + name + "\t" + fmt.format(balance));
   }
}



Transactions.java


//********************************************************************
//  Transactions.java       Author: Lewis/Loftus
//
//  Demonstrates the creation and use of multiple Account objects.
//********************************************************************

public class Transactions
{
   //-----------------------------------------------------------------
   //  Creates some bank accounts and requests various services.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      Account acct1 = new Account ("Ted Murphy", 72354, 102.56);
      Account acct2 = new Account ("Jane Smith", 69713, 40.00);
      Account acct3 = new Account ("Edward Demsey", 93757, 759.32);

      acct1.deposit (25.85);

      double smithBalance = acct2.deposit (500.00);
      System.out.println ("Smith balance after deposit: " +
                          smithBalance);

      System.out.println ("Smith balance after withdrawal: " +
                          acct2.withdraw (430.75, 1.50));

      acct1.addInterest();
      acct2.addInterest();
      acct3.addInterest();

      System.out.println ();
      System.out.println (acct1);
      System.out.println (acct2);
      System.out.println (acct3);
   }
}



More Examples: Rectangle, and Circle


public class Rectangle
{
    private double height=1.0;
    private double width =1.0;

    public Rectangle(double h, double w)
    {
        height = h;
        width =w;
    }

    // Note that the compiler won't provide me a default
    // constructor if I have added any other constructor.

    public Rectangle()
    {
    }

    public double getHeight()
    {
        return height;
    }

    public double getWidth()
    {
        return width;
    }

    public void setHeight(double h)
    {
        height = h;
    }
    public void setWidth(double w)
    {
        width = w;
    }
    public double perimeter()
    {
        return 2.0 * (width + height);
    }

    public double area()
    {
        return width * height;
    }

}

public class Circle
{
    // Note that I can just let radius be initialized by the constructor
    private double radius;

    public Circle(double r)
    {
        radius = r;
    }
    public Circle()
    {
        radius = 2.0;
    }

    public double getRadius()
    {
        return radius;
    }
    public void setRadius(double r)
    {
        radius = r;
    }
    public double perimeter()
    {
        return 2.0 * Math.PI * radius;
    }
    public double area()
    {
        return Math.PI * radius * radius;
    }

}

public class Test
{
    public static void main(String[] args)
    {
        Rectangle r1 = new Rectangle();
        Rectangle r2 = new Rectangle(3.0, 4.0);

        System.out.println("r1: perimeter="+ r1.perimeter());
        System.out.println("r1: area="+ r1.area());

        System.out.println("r2: perimeter="+ r2.perimeter());
        System.out.println("r2: area="+ r2.area());

        Circle c1 = new Circle(5.0);
        Circle c2 = new Circle();

        System.out.println("c1: perimeter="+ c1.perimeter());
        System.out.println("c1: area="+ c1.area());

        c2.setRadius(10.0);

        System.out.println("c2 has a radius of:"+ c2.getRadius());
        System.out.println("c2: perimeter="+ c2.perimeter());
        System.out.println("c2: area="+ c2.area());

    }
}


Another approach



class Circle
{
    // Note that I can just let radius be initialized by the constructor
    double radius;

    Circle(double r)
    {
        radius = r;
    }
    Circle()
    {
        radius = 2.0;
    }
    double perimeter()
    {
        return 2.0 * Math.PI * radius;
    }
    double area()
    {
        return Math.PI * radius * radius;
    }

}

public  class Test
{
    public static void main(String[] args)
    {
        Circle c1 = new Circle(5.0);
        Circle c2 = new Circle();

        System.out.println("c1: perimeter="+ c1.perimeter());
        System.out.println("c1: area="+ c1.area());

        c2.radius = 10.0;

        System.out.println("c2 has a radius of:"+ c2.radius);
        System.out.println("c2: perimeter="+ c2.perimeter());
        System.out.println("c2: area="+ c2.area());

    }
}


Once you have written one constructor such as
Rectangle(double h, double w)
your compiler will no long provide a default constructor. At this point if you want a constructor with no parameters (default constructor), then you need to provide it as shown above.

Exercises:

1. What does the keyword public do for you on a method or a variable?
2. What does the keyword private do for you on a method or a variable?
3. What does it mean for a method to return a value?
4. Is a return statement required?
5. Explain the difference between an actual parameter and a formal parameter.
6. What are constructors used for? How are they defined?
7. Write a method called cube that accepts one integer parameter and returns that value raised to the third power.
8. Write a method called random100 that returns a random integer in the range of 1 to 100 (inclusive).
9. Write a method called randomInRange that accepts 2 integer parameters representing a range. The method should return a random integer in the specified range(inclusive). Assume that the first parameter is greater than the second.
10. Create a class that generates random password sequences. Consider adding methods such as:
Password()
Password(int num)
replace()
replace(int num)
toString()
equals(Password p)
11. Design and implement a class called Dog that contains instance data that represents the dog's name and age. Include a method to compute and return the age of the dog in "person years" (seven times the dogs age). Include a toString method. Create a driver class called Kennel whose main method instantiates and updates several Dog objects.
12. Design and implement a class called Book that contains instance data for the title, author, publisher, and copyright date. Define the Book constructor such that everything gets initialized. Create a driver class called Bookshelf, whose main method instantiates and updates several Book objects.
13. Design and implement a class called Flight that represents an airline flight. Each instance should contain airline name, flight number, and the flight's origin and destination cities. Create a driver class called FlightTest, whose main method instantiates and updates several Flight objects.
14. Create a class called PairOfDice which is composed of 2 Die objects. Provide a method to roll both Dice. Provide a method to return the sum of the 2 Tice.
15. Create a class called Fraction. Provide methods for add, subtract, multiple, and divide. See if you can figure out a way to reduce your fraction. Provide a toString method.
16. Create a Person class that has name, and age. Provide various constructors with various defaults. The Person class should have a String variable that keeps track of the Person's attributes. Add a method called addAttribute to the Person class to append new attributes.
17. Add to the Person class a variable named:
Person marriedTo = null;
Create a method to marry 2 Persons. This method can be a static method that takes in 2 Person classes. We can also have a divorce method.

Last Modified: February 6, 2008 11:49 AM