The Keyword final with Classes and Methods

In Chapter 2 we looked at the keyword final for declaring constant variables, ones that could not be changed once initialized. The use of the keyword final also translates to use with classes and methods. Include the keyword final in the declaration of a class (for example, in the Alien class):

public final class Alien extends Creature {     //  Code here }

This means that no other class can be derived from the Alien class. For example, the following class would not compile if our Alien class were declared as final.

public class Martian extends Alien  {     //  Alien is final and that's final!     //  No code here :( - will not compile }

The keyword final when used with methods means that the method cannot be overridden in any subclass. For example, we could declare the speak method of the Creature class as final.

public class Creature {     public final void speak(String greeting)     {         System.out.println("Creature says: " + greeting);     } }

This means that the Alien and Human subclasses of Creature would not be able to implement their own versions of the speak method.



Java 1.4 Game Programming
Java 1.4 Game Programming (Wordware Game and Graphics Library)
ISBN: 1556229631
EAN: 2147483647
Year: 2003
Pages: 237

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net