Google
 
Site navigation: [ Home | Theory | Java | Moodle courses | Resource wiki | About ]

Classes and methods

Encapsulation

The inclusion of data and the methods that act on that data into a single discrete unit is known as encapsulation and has proved a major step forward in more reliable program design.

These are the data members or instance variables of the Class.

Keeping them private means they can't be acccessed from outside of the Class Fraction.

A Constructor is a special method that creates a new instance of the Class. It has no return type.

There can be more than one Constructor as long as the parameters are different in number and/or type.

This is a method. A static method can be accessed without an object (instance) of Class Fraction being created. Similar to the method parseInt() of the Integer Class which we saw in AddTwo .

Notice that this method returns an instance (object) of type Fraction. The use of new calls the corresponding constructor .


Also on this page: [ constructors | static methods | common problems ]

Classes

Classes are one of the central concepts of Java and object-oriented programming in general. We have seen a special type of Class so far which is the Applet. Here we look at a Class which represents a data object - a fraction data type.

Unlike an Applet or an IBIO Class, you can't run the Fraction Class it's an object something more like a String.

A Class consists of data members and methods . Data members hold the properties of a Class, they are often (but not always) one of the primitive types we have already met. Methods, as we have seen, are discrete blocks of code and they determine the behaviour of the Class (what it does).

Class Fraction

/**
* A Class for implementing the data type fraction
*
* @author Mr J
* @version 20040212
*/

public class Fraction
{
   private int numerator;   // top part
   private int denominator; // bottom part
/**
* Constructor for objects of class Fraction
*/

   public Fraction()
   {
   // initialise instance variables
     numerator = 0;
     denominator = 1;
   }
   /**
   * Construct a fraction given two ints (numerator first)
   *
   * @param n the numerator
   * @param d the denominator
   */

   public Fraction(int n, int d)
   {
     // initialise instance variables
     numerator = n;
     denominator = d;
   }

  /** A method to add two fractions
   *
   * @param a a Fraction
   * @param b another fraction
   * @return the sum of fractions a and b
   */

   public static Fraction add(Fraction a, Fraction b)
   {
     // find the common denominator, multiply the numerators
     int cd = (a.denominator * b.denominator);
     a.numerator = a.numerator * b.denominator;
     b.numerator = b.numerator * a.denominator;
     // now add them
     int nm = a.numerator + b.numerator;

     // here we should factorise, too hard for now!
     // just return a fraction instance

     return new Fraction(nm, cd);
   }
   /**
   *
   * @return a String representation of the Fraction
   */

   public String toString()
   {
     return("" + numerator + "/" + denominator);
   }
}

Back to top

Constructors

Constructors are special methods that create a new instance of a Class. There is no significant difference between the term object and the term instance in the way we use them here.

A constructor is called with the new keyword, you cannot call it directly - a call to Fraction.Fraction() or even a.Fraction() would cause an error. Constructors should only be used for initialization of data members (also known as instance variables or even instance fields).

Even if a Constructor does not appear to be present in a Class Java supplies a hidden constructor method behind the scenes.

Multiple constructors are possible but each one has to have a different signature (the parameter list can't contain the same number and type of variables).

Back to top

Static methods (and identifiers)

The static keyword is used to identify methods and data members which are accessible by all members of a Class and which don't "belong" to any one instance (created with new). Static methods are useful when you don't want to instantiate (create with new) an object but do want to use the method. Static methods are preceded by the Class name:

Integer.parseInt(String s);
Fraction.add(Fraction a, Fraction b);

for example.

Back to top

Common problems with methods and constructors

Methods that look like constructors and hidden data members.

This looks like a constructor but it isn't (why not?):

  public void Fraction(int n, int d)
   {
     // initialise instance variables
     numerator = n;
     denominator = d;
   }

It can cause problems in compilation which are hard to find or even in execution sometimes. It is good practice to use identifiers that start with lower case letters as it helps to spot this kind of problem.

Because sometimes confusion can occur between data members and local variables or parameters with the same name it is always good to place the this keyword before data members wherever they appear in code:

  public Fraction(int n, int d)
   {
     
// initialise instance variables
     this.numerator = n;
     this.denominator = d;
   }

It won't always be strictly neccessary but it is good practice. For example, this code may appear to set the numerator value, but it doesn't:

  public void setNumerator(int n, int d)
   {
     int numerator = 0;  // local variable
     
// set Class data member (not)
     numerator = n;
   }

This may be easy to spot in a small example but when you have methods extending over 20 or 30 lines it can be difficult to trace such an error. In this case the local variable numerator is changed and the Class data member numerator is not.

This, on the other hand, will always behave as expected:

  public void setNumerator(int n, int d)
   {
     int numerator = 0;  // local variable
     // set Class data member (OK)
     this.numerator = n;
   }


Back to top

Next: We look at how we can use the Fraction Class in an Applet.

Related: [ Java Home | previous:Arithmetic | next:using Fraction.java ]

Teaching notes

If you are going to attempt to give your students some good knowledge about Java and OOP (and you might as well) then introducing it as early as they can handle it is probably a good idea.


 
The site is partly financed by advertising revenue, partly by online teaching activities and partly by donations. If you or your organisation feel these resouces have been useful to you, please consider a donation, $9.95 is suggested. Please report any issues with the site, such as broken links, via the feedback page, thanks.

Questions or problems related to this web site should be addressed to Richard Jones who asserts his right to be identified as the author and owner of these materials - unless otherwise indicated. Please feel free to use the material presented here and to create links to it for non-commercial purposes; an acknowledgement of the source is required by the Creative Commons licence. Use of materials from this site is conditional upon your having read the additional terms of use on the about page and the Creative Commons Licence. View privacy policy.

Creative Commons License


This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. © 2001 - 2009 Richard Jones, PO BOX 246, Cambridge, New Zealand;
This page was last modified: May 31, 2009