13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

3.4 Encapsulati<strong>on</strong>, Inheritance, and Polymorphism89private String hidn;String pkgstr;protected String protstr;public String wideOpen;3.4.2.2 The static statementAnother keyword qualifier <strong>on</strong> declarati<strong>on</strong>s that we need to describe is thestatic keyword. When a variable is declared static then there is <strong>on</strong>ly <strong>on</strong>einstance of that variable shared am<strong>on</strong>g all instances of the class. Since the variableexists apart from a particular instance of the class, <strong>on</strong>e refers to it with theclass name followed by a dot followed by the variable name, as in System.out.Similarly, methods can be declared static as well. This also means thatyou d<strong>on</strong>’t need an instance of the class to call them, just the class name, as inSystem.getProperties().Now with Java 5.0, you d<strong>on</strong>’t even need the class name, provided that youhave a static import statement at the top of your class, for example:import static java.lang.System.*;3.4.2.3 The final statementAnother way that static is often seen is in c<strong>on</strong>juncti<strong>on</strong> with the final keyword.When a variable is declared final then a value can be assigned to it <strong>on</strong>ce,but never changed. This can make for good c<strong>on</strong>stants.Since public will make the variable visible to all other classes, staticwill make it a class variable (available without an instance of that class), andfinal will keep it from being altered (even though it is publicly available), thencombining all of those gives us a good declarati<strong>on</strong> for a c<strong>on</strong>stant, for example:public static void l<strong>on</strong>g lightSpeed = 186000;// mpsNew to Java 5.0 is the explicit creati<strong>on</strong> of enumerated types. Prior to 5.0,programmers would often use static final c<strong>on</strong>stants even when the particularvalue was unimportant, as a way to provide compile-time checking of theuse of the c<strong>on</strong>stant values. Here is an example of a declarati<strong>on</strong> of a set ofenumerated values:enum WallMods { DOOR, WINDOW, VENT, GLASSBLOCK };

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!