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

Chapter 4 Advanced Class Design

final class Canvas { /* members */ }

class ExtendedCanvas extends Canvas { /* members */ }

If you try to extend a final class, as you just tried to do, you’ll get the compiler error "cannot inherit from final Canvas".

Final Methods and Variables

In a class, you may declare a method final. The final method cannot be overridden. Therefore, if you have declared a method as final in a non-final class, then you can extend the class but you cannot override the final method. However, other non-final methods in the base class can be overridden in the derived class implementation.

In the FunPaint application, for instance, one method is final (setParentShape()) and another method is non-final (getParentShape()), as shown in Listing 4-1.

Listing 4-1.  Shape.java

public abstract class Shape { //class members...

final public void setParentShape(Shape shape){ //method body

}

public Shape getParentShape(){ //method body

}

}

In this case, the Circle class (subclass of Shape) can override only getParentShape(); if you try to override the final method, you will get following error: "Cannot override the final method from Shape".

Finally, we mention final variables. Final variables are like CD-ROMs: once you write something on them, you cannot write again. In programming, universal constants such as PI can be declared as final since you don’t want anyone to modify the value of such constants. Final variables can be assigned only once. If you try to change a final variable after initialization, you will get a complaint from your Java compiler.

Points to Remember

Master the following points, as they might well come up in the OCPJP 7 exam:

The final modifier can be applied to a class, method, or variable. All methods of a final class are implicitly final (hence non-overridable).

A final variable can be assigned only once. If a variable declaration defines a variable as final but did not initialize it, then it is referred to as blank final. You need to initialize a blank final all the constructors you have defined in the class; otherwise the compiler will complain.

The keyword final can even be applied to parameters. The value of a final parameter cannot be changed once assigned. Here, it is important to note that the “value” is implicitly understood for primitive types. However, the “value” for an object refers to the object reference, not its state. Therefore, you can change the internal state of the passed final object, but you cannot change the reference itself.

91

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