Google
 
Site navigation: [ Home | Theory | Java | About ]

Object Oriented Programming

This page could be used as a starting point in a totally Object-oriented course.

However, it is written under the assumption that the material in the core section has already been covered. It attempts to provide the theoretical framework underpinning object-oriented programming and design .

 

 

A key opens something.

This key opens my front door.

 

 

References appear at the bottom of this page.

 

 

A Class has properties that are (usually) common to all actual objects in that Class.

 

 

 

 

The this keyword is not strictly neccessary as Java will assume the Constructor refers to the data members - but it is good programming practice .

Bus 431 used to run from Orpington Railway Station, via Chelsfield, Halstead, Knockholt, Dunton Green, and Riverhead to Sevenoaks Bus Station. Perhaps it still does.

Software re-use cuts down programming time and increases software reliability .

 

 

 

 

 

 

 

 

 

 

Students are required by IB to know about public and private data members and methods but not protected.

 

 

 

Use of methods with a return type is a mastery factor

 

 

 

 

 

 

Use of methods with parameters is a mastery factor

 

 

 

 

 

 

 

 

 

 

 

 

Identifiers (names) for methods that are not Constructors should always start with a lowercase letter.

 

 

 

 

 

 

 

Use of pre and post conditions is part of dossier requirements , criterion B2 at higher levels of achievement.

The IB can't really expect students to be completely familiar with all the ramifications of pre and post conditions so their use at a relatively simple level should be acceptable.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

See also http://bluej.org

   On this page :    [ objects | objects in Java | applications | method signatures ]
                              [ programming by contract | Bibliography and references ]

   Related links:      [ terminology | intro to Java Classes | more about Classes ]
                            [ Exceptions | inheritance | BinaryQuiz example | Exercises ]

Objects and Classes

Clearly objects have to be the core of an object-oriented programming approach. An object is a basic unit of programming in the same way that our common machines are built from more basic units.

My laptop computer has many parts, some, like the keyboard are collections of similar parts . A key with the letter Q marked on it is an example of an object .

Objects in software are abstract rather than physical , so we tend to work with a physical example and then move to abstract concepts.

You could say that keys on a keyboard are a class of object - they all have the same basic behaviour . However each individual key is different in some way, it has different properties (like the letter marked on the top).

A Class therefore describes a set of objects which have something in common. Notice that you cannot actually press keys in the abstract description , you can only press a particular key.

Similarly, buses are a common form of transport but if we want to ride one, we get on one that has a number, a colour, a size, a shape, it's full or empty - it has properties .

See also the book by Barnes and Kolling written to accompany the BlueJ IDE.

Back to top

A Java bus Class might look like this:

public Class Bus
{
   int routeNumber;     // properties or attributes of the Class Bus
   String colour;
   int numberOfSeats;   // We also call these data members of the Class
   String type;
   boolean full;        // It would be good practice to make them private too
}

An object (or more correctly an instance ) of the Bus Class has to have data supplied for these data members . The creation of a Bus instance is done via the Constructor (a special method with the same name as the Class - see the methods page ).

public Bus( int r, String c, int s, String t, boolean f)
{
   this.routeNumber = r;
   this.colour = c;
   this.numberOfSeats = s;
   this.type = t;
   this.full = f;)
}

The constructor is always called with the new keyword:

  Bus aBus = new Bus(431, "green", 35, "single deck", false);

This line of code might typically be found in another Class (typically an Applet or Application) that actually needs to use it, for example a bus timetabling (scheduling) application.

Objects are frequently designed with multiple use (or re-use ) in mind, for example awt objects such as TextField's and Button's are examples of re-usable objects.

Back to top

Applications

Applications are both objects themselves and often composed of a group of cooperating or related objects. These objects need to communicate with each other and sometimes to change state (a bus might be re-painted or change route).

Objects communicate via the use of methods . We have seen what these are already (see this page ) - they are discrete blocks of java code identified with a name (or identifier ).

public boolean isFull(int route)
{
   // find the route object in the bus collection and return true if this
   // instance is full.

}

We'll look at each of the keywords that make up the method header in turn. The term signature is often used and, according to whose making the definition, might or might not include the return type, identifier and parameter list.

public is the access specifier - public means it can be accessed from outside of the Class where it is defined. This is how communication among objects in an application is achieved.

A private method can only be accessed by methods within the same Class - often called helper methods . They are frequently used to break a large task down into smaller units.

A protected method is accessible by methods which extend a given Class (see the topic inheritence in the HL part of the course).

boolean is the return type . A method wich is not void must return a single value via use of the return statement, the above method would have at least one (possibly more) statements returning a boolean primitive:

   return true;

Methods can also have user-defined and built-in class types as return types:

    public Bus getBusOnRoute(int route)

   private TextField getTextObject()

The identifer is a name given by the programmer and by convention always starts with a lowercase letter (except for the Constructor method). It cannot start with a number or contain spaces or other special characters.

The parameter list can be empty or contain one or more parameters. each parameter in the list is preceded by its type which can be a primitive or Class type. The following method gets an int from TextField:

public int getPositiveInteger(TextField tf, int lower, int upper)
{
   int x = Integer.parseInt(tf.getText().trim());
   if ( (x >= lower) && (x <= upper) )
   {
     return x;
   }
   return -1;
}

Back to top

The combination of access specifier, return type, identifier and parameter list is known as the header. The combination of return type, identifier and parameter list is known by many authors as the method signature.

Two methods can have the same identifier as long as at least one of the other elements is different, thus, the following would be a valid method in the same class as getPositiveInteger above:

public int getPositiveInteger(TextField tf)
{
   return Integer.parseInt(tf.getText().trim());
}

It might not do the job it says it does but that's a diffierent issue.

Constructors, like other methods, can have different signatures (the name will always be the same because it will be the name of the Class). While we are discussing this, do not attempt to put a return type with a constructor , this can be a very hard to spot error!

public void Bus( int r, String c, int s, String t, boolean f) // oops! wrong!
{
   this.routeNumber = r;
   this.colour = c;
   this.numberOfSeats = s;
   this.type = t;
   this.full = f;)
}

Back to top

Programming by Contract

Back in 1997, a programmer called Bertrand Meyer wrote the book on OOP. One of the key ideas was to "Design by Contract ".

A contract is an agreement, usually between two humans, which sets out the rights and obligations of each party.

Methods do things to objects or return information about objects. Design by contract attempts to set pre-conditions and post-conditions for every method.

A pre-condition states what must be true for the method to execute successfully . It should never be called when these pre-conditions are not true. This is not the same as making sure that data passed is acceptable , rather it indicates that something drastic has gone wrong (there is a bug in the program).

Consider the method we looked at earlier:

public int getPositiveInteger(TextField tf, int lower, int upper)
{
   int x = Integer.parseInt(tf.getText().trim());
   if ( (x >= lower) && (x <= upper) )
   {
     return x;
   }
   return -1;
}

It should be a precondition that the TextFiedl tf contains a valid integer - if it doesn't the return value is wrong. The contract of the routine is:

If the tf field does contain a valid integer , this routine returns it as an int in the range lower >= return value >= upper OR it returns -1 if it is outside this range. In other words it will do what it is designed to do .

If the tf field does NOT contain a valid integer , this method does not promise anything . It will not catch error such as the user entering 4.56 in the TextField.

This is a programmer's contract not a user's contract. If the method is called with an invalid String in the text field that's too bad - don't complain that it didn't work properly - as long as it is in the pre-condition:

/**
* getPositiveInteger
* precondition: The TextField tf contains a String which represents a valid *               integer
*/

public int getPositiveInteger(TextField tf, int lower, int upper)
etc

A post-condition on the other hand is a guarantee by the method of what it will do (if the pre-conditions are met). A post-condition for the above method might read:

/**
* getPositiveInteger
* precondition: The TextField tf contains a String which represents a valid *               integer
* postcondition: An integer in the range lower-upper inclusive is returned
*                or the value -1, if the input was outside this range.
*/

public int getPositiveInteger(TextField tf, int lower, int upper)
etc

Andrew Hunt and David Thomas recommend that you "promise to deliver as little as possible" and "be strict in what you will accept" .

Back to top

Bibliography and References

Andrew Hunt and David Thomas , 2000, The Pragmatic Programmer, Addison-Wesley, Boston, USA
Bertrand Meyer , 1997 , Object Oriented Software Construction, Prentice Hall, New Jersey, USA.
David Barnes and Michael Kolling , 2003, Objects first With BlueJ, Pearson education, Harlow, Essex, UK.

 

Related: [ Java Home | next:Classes]

Objects as an HL topic only appear in the pages on Data Structures

This section can be skipped with no loss of continuity for teachers and students who just wish to use traditional (and increasingly out-dated) procedure-based programming techniques.



 
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: October 28, 2013