Tuesday, January 8, 2013

Sorting types: Run time class

DOWNLOAD THE CODE: RuntimeTypeSearch

Consider the inheritance hierarchy in the diagram below:


A collection, such as ArrayList may be of a general type..

For instance:

ArrayList<Superclass> list = new ArrayList<Superclass>();

All objects of Superclass type may be added to the list.

For instance:

add(new Superclass());
add(new SubClassWhite());
add(new SubClassBlack());
add(new SubClassA());
add(new SubClassB());
add(new SubClassX());
add(new SubClassY());

The list now contains 7 objects, all of type Superclass. Even though many of the objects are specialisations of Superclass, they all have the context of Superclass.. This means we can only use each object as the general type (Superclass), regardless of its specialisation.

Getting the specific type of an object
If we want to discover the actual run time type of each object in the list, we call the getClass() method. This method is inherited by all objects from the Object class and returns the run time class of the object.

The equals() method (also inherited from Object) performs an equality check on the current object in the list, with the class name we are looking for.

if (list.get(6).getClass().equals(SubClassWhite.class) {
   //
}

If this expression evaluates to true, we are then able to cast the general object type into it’s specialised type:

SubClassWhite s = (SubClassWhite)list.get(6);

The object called s is now of type SubClassWhite and may be used in the context.

Full code listing (including a loop to iterate through the list) which finds objects in the list with the run time type of SubClassWhite and casts it accordingly.:

ArrayList<Superclass> list = new ArrayList<Superclass>();
add(new Superclass());
add(new SubClassWhite());
add(new SubClassBlack());
add(new SubClassA());
add(new SubClassB());
add(new SubClassX());
add(new SubClassY());

for (int x = 0; x < list.size(); x ++) {
   if (list.get(x).getClass().equals(SubClassWhite.class) {
       SubClassWhite s = (SubClassWhite)list.get(x);
   }
}

Getting the general type of an object
If we want to find all instances of SubClassWhite (remember that SubClassWhite is a subclass of Superclass but also a superclass itself) we use the instanceof operator. Using this method, all instances of SubClassWhite, SubClassX and SubClassY will be discovered.


for (int x = 0; x < list.size(); x ++) {
   if (list.get(x) instanceof SubClassWhite.class) {
       SubClassWhite s = (SubClassWhite)list.get(x);
   }
}

What is an Interface?

DOWNLOAD THE CODE: InterfaceExample

An interface specifies the behaviours that should be present within all classes that implement (use) it. An interface contains method signatures only. There is no method implementation - there is no method body. See class diagram below:



Each behaviour defined in the interface must be implemented (coded) in any classes that implement (use) it.

The implements keyword is used to implement an interface in a class. The figure below shows the class declaration for the Person class which has been modified to implement the class called IPerson.





Interface naming convention
The naming convention for an interface is a capital I followed by a meaningful name. As the interface in this example was only designed to be used with the Person class, I have called it IPerson.

Why use an interface?
Interfaces provide a standard and consistency for communication between classes and other parts of a system.

Consider the teacher who gives her students the outline for the functional requirements of a system. Each student produces a design and implementation but has perhaps forgotten to include methods, method parameters or simply used different spelling for method names. The student adds the teachers test harness to the code but is immediately faced with compilation errors due to misspelling & missing detail.

For the next project however, as well as giving the students the functional requirements of a system, the teacher also gives them a number of interfaces to develop to, ensuring that all methods, method parameters & spelling, as used by the test harness, will be implemented in the students code.

Multiple interfaces
A class may implement many interfaces.




In the diagram above, the Weapon class implements both the IStats and IBattle interface. This means that the Weapon class must implement the methods which are present in both interfaces.

The Weapon class can now be used in the context of IStats and IBattle type.


Interface as type
Where a class implements an interface, objects of that class may be treated as objects of the interface type.

For instance:

ArrayList<IBattle> battleObjectList = new ArrayList<IBattle>();
battleList.add(new weapon);
battleList(new Arena());

All objects in the list have the context of IBattle and only the methods specified in the IBattle  interface are accessible.


Java Interfaces
As well as the interface types you will write yourself, there are numerous predefined interface types in the Java API such as MouseListener, List, Map.

See also:
"What Is an Interface? (The Java™ Tutorials > Learning the Java Language > Object-Oriented Programming Concepts)" ( http://bit.ly/Rph8eP )

Friday, December 21, 2012

Consider if 2 objects are equal....

Demo Code Project: OverridingEquals.zip

Let's say you have the need to ensure that no 2 objects have the same contents - you want to check if one object is equal to another?

What do you consider equal?

Read on...

equals(Object)
The default implementation of the equals method, provided in all java objects (java.lang.Object) is to compare the memory location of one object, with another.


Consider the example above.

Two objects of type Asteroid1 have been instantiated using identical parameters - both a1 and a2 objects have the same contents. They do not, however, have the same memory location.

When the new operator is used, it causes the system to allocate memory space for the data and as such, a1 and a2 objects have unique memory locations.

When the equals method is used to compare the equality of these 2 objects, the equals method will return false - because each object has a different memory location.

If, for the purposes of your program, you consider that object equality is based on memory location only, the default implementation of the equals method is sufficient.

If however, you consider that object equality is based on the contents of objects themselves (more likely), read on...

overriding equals(Object)

All java objects (java.lang.Object) contain a default implementation of an equals method which compares the memory location of objects to determine equality. When writing your own libraries, you may find that this version of the method is not fit for your purpose. In this case, you can override the method and implement your own version of what you consider to be equality. It is usually the case that object equality relies on comparing the contents of the objects - not the memory locations.

When a class overrides a method, it is providing it's own version of a method that has already been provided by it's parent class (such as java.lang.Object).

You can override the equals method simply by providing your own, in your class. A couple of things to remember though:

The method signature must be the same as the one provided by java.lang.Object:

  • Public
  • Boolean return type
  • method name must be equals
  • takes a single parameter of Object type

...which looks like...



OK, now for the implementation. Our goal is to compare the contents of the object parameter with the contents of the current object.

Here is the definition of the class called Asteroid2:



Note that the equals method has been included in the method list.

The contents of this class are the values for the name, size and rotationRate fields. In our implementation of equals, we will write code which considers equality based upon the values of these fields.

Basically, if the current object has the same name as the parameter object and the current object has the same size as the parameter object and the current object has the same rotationRate as the parameter object, we will consider the current object and the parameter object to be equal.

Here's the code:






The first line ensures that the parameter object (aThat) being passed to the method is of the correct type - in this case Asteroid2. The instanceof operator (compares an object to a specified type) is used to determine the type. The method returns false immediately if this is not found to be true - after all, if the parameter object isn't of type Asteroid2 then it will never be equal to any instance of Asteroid2.

The second line then goes ahead and casts (converts) the parameter object to the type it is being compared to - in this case, Asteroid2. Once the cast has taken place, we can then treat the parameter object (aThat) as an instance of Asteroid2 (That) and call each of it's methods to begin determining equality.

The return statement uses the logical operator && to join together a number of expressions, relating to the fields on the objects, which will ultimately evaluate to true or false.

Once again...basically, if the current object has the same name as the parameter object and the current object has the same size as the parameter object and the current object has the same rotationRate as the parameter object, the method will return true.

Calling the equals method
Let's assume that we wish to add a new Asteroid2 object to an existing ArrayList of Asteroid2 objects but we want to make sure that an object with the same contents does not already exist in the ArrayList.

The example below uses a loop to compare the new Asteroid2 object with each object in the ArrayList:


Because the Asteroid2 class has overriden equals, we can be assured that only objects containing unique contents will be added to the ArrayList.

Incidentally, the ArrayList has a contains method which evaluates object equality in the same way - dispensing with the need for a loop. It simply calls the equals method on each object in the ArrayList - equality is based on whether the method has been overriden by the class in question (contents) or not (memory location).

One last thing...

We can also quickly return from the equals method by checking if the parameter object has the same memory location (and hence is the *same* object) as the current object.


When the equal to operator (==) is used on objects (reference types), the references (memory locations) are compared.

see also:

"Object (Java Platform SE 7 )" ( http://bit.ly/YrEmpk )

"Overriding and Hiding Methods (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)" ( http://bit.ly/Zn8eop )


member access operator (.)

In Java, the dot (.) is an operator called the member access operator.

This operator is used to separate the class/object name from a method name.

For instance, an object called playerOne that has a method called fight:

playerOne.fight()


Monday, September 24, 2012

Modulo %

Download the code

This operator returns the remainder of division of one number by another number.


Integer examples
For instance, 10 / 2 has a remainder of 0. This is because 10 is divided by 2, exactly.
Another example, 15 / 2 has a remainder of 1. This is because, after division has taken place (15 can be divided 7 times), 1 is left over.
More examples:

The remainder of an integer division only returns the integer part of the result.
For instance, if you were to type 4 / 3 into a calculator, you would see the result is 1.3333333 etc. However, where this calculation is being performed as integer division in a programming language, such as java, only the integer part is returned - producing the result 1.


Generating a random number

also see Using the Random class to generate a random int

The Math class contains a static method for random number generation.

To generate a single random int between 0.0 and 1.0 you can use the following:

int number = (int)(Math.random() * 10);


This method returns a value from 0.0 to 0.9. A whole number, from 0 to 9, can be produced by multiplying the result by 10.

Note that casting has been used to convert the return value, which is a double, to int.

And remember, static class methods may be called without creating an instance of the class.

Where many random numbers with a larger range are required, see java.util.Random such as below:

In this example we are going to generate random numbers between 1 and 100:


The statement rand.nextInt(100) + 1 gets the next random number in the range of 1 - 100 inclusive. Need a large number? Adjust to suit.