Presentation is loading. Please wait.

Presentation is loading. Please wait.

Objects First With Java A Practical Introduction Using BlueJ Casting Week 22 2.0.

Similar presentations


Presentation on theme: "Objects First With Java A Practical Introduction Using BlueJ Casting Week 22 2.0."— Presentation transcript:

1 Objects First With Java A Practical Introduction Using BlueJ Casting Week 22 2.0

2 2 Main concepts to be covered Casting numbers Casting objects The instanceof operator

3 3 Casting numbers We can easily assign an int to a double because there is no possibility of a loss of precision In the following example, the value 3.0 will be assigned to d int i = 3; double d = i;

4 4 Casting numbers There would be a compilation error though if we tried to write: double d = 3.9; int i = d; If we want to assign a double to an int (or, for example, to a float) then we need to tell the compiler that we accept the possible loss of precision

5 5 Casting numbers This process is known as casting We need to cast the number to an int by writing (int) in front of it In the following example, the value 3 will be assigned to i double d = 3.9; int i = (int) d;

6 6 Casting objects Consider the dome-v2 project The CD class has the following method to return the number of tracks public int getNumberOfTracks() { return numberOfTracks; }

7 7 Casting objects Suppose we wanted to write a method in the Database class to print the number of tracks of a CD that was stored at a particular position in the array list The Item object returned from the get method would need to be cast into a CD object in order to call the getNumberOfTracks method

8 8 Casting objects public void printNumberOfTracks(int index) { CD cd = (CD) items.get(index); System.out.println("The number of tracks on the CD is " + cd.getNumberOfTracks()); }

9 9 The instanceof operator The printNumberOfTracks method could be improved by checking whether the returned Item object is actually a CD object, and only casting it to CD if it is. This could be achieved using the instanceof operator. The expression anObject instanceof AClass evaluates to true if the type of anObject is AClass (or some subclass of Aclass). Otherwise it evaluates to false.

10 10 The instanceof operator public void printNumberOfTracks(int index) { Item item = items.get(index); if (item instanceof CD) { CD cd = (CD) item; System.out.println("The number of tracks on the CD is " + cd.getNumberOfTracks() + "."); } else { System.out.println("The item is not a CD."); }

11 11 Review Casting can be used with numbers to, for example, assign a double to an int. Casting can be used with objects when it is required to call a method that only exists in a subclass of the declared type. The instanceof operator can be used to check the type of an object.


Download ppt "Objects First With Java A Practical Introduction Using BlueJ Casting Week 22 2.0."

Similar presentations


Ads by Google