Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 3 Java Class Design

1.Providing exception handlers for RuntimeExceptions like this create an illusion that the program is working perfectly fine, when it is not!

2.Runtime exceptions like ClassCastException indicate programming errors and should not be caught using exception handlers.

Okay, so what do you do now? Before downcasting, check for the dynamic type of the object and then downcast.

StringBuffer str = new StringBuffer("Hello"); Object obj = str;

if(obj instanceof String) {

String strBuf = (String) obj;

}

This is an effective and proper way to achieve downcasting. Using the instanceof operator checks the dynamic type of obj, which helps you to decide whether to downcast it to a String object.

Coming back to the example of FunPaint, you have the abstract base class Shape and many derived objects like Square, Circle, etc. You might need to perform typecasting in order to execute conversions between the base type and the derived types. Here is an example:

Shape shape = canvas.getHighlightedShape(); Circle circle = (Circle) shape; circle.redraw();

Here, assume that there is a method called getHighlightedShape() that returns the current highlighted Shape on the canvas. In the statement Circle circle = (Circle) shape;, you are downcasting from the Shape type to the Circle type. However, this is dangerous because if Shape holds a Square object, then this downcast will fail. To avoid that, you need to use operator instanceof before downcasting, like so:

Shape shape = drawingWindow.getHighlightedShape(); if(shape instanceof Circle) {

Circle circle = (Circle) shape; circle.redraw();

}

it is a bad practice to handle runtime exceptions like ClassCastExceptions. instead, it is better to introduce defensive programming checks to avoid such exceptions at runtime.

Java Packages

When the size of your application grows, you need an effective mechanism to manage all your source files. Java supports the concept of package, which is a scoping construct to organize your classes and to provide namespace management. All closely related classes can be put together in a single entity: a package. A package not only reduces the complexity of a big application but also provides access protection.

77

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]