|Access||Adobe photoshop||Algoritmi||Autocad||Baze de date||C||C sharp|
|Calculatoare||Corel draw||Dot net||Excel||Fox pro||Frontpage||Hardware|
|Php||Power point||Retele calculatoare||Sql||Tutorials||Webdesign||Windows|
|Asp||Autocad||C||Dot net||Excel||Fox pro||Html||Java|
Because any fields you put into an interface are automatically static and final, the interface is a convenient tool for creating groups of constant values, much as you would with an enum in C or C++. For example:
Notice the Java style of using all uppercase letters (with underscores to separate multiple words in a single identifier) for static final primitives that have constant initializers Ė that is, for compile-time constants.
The fields in an interface are automatically public, so itís unnecessary to specify that.
Now you can use the constants from outside the package by importing c07.* or c07.Months just as you would with any other package, and referencing the values with expressions like Months.JANUARY. Of course, what you get is just an int so there isnít the extra type safety that C++ís enum has, but this (commonly-used) technique is certainly an improvement over hard-coding numbers into your programs. (This is often referred to as using ďmagic numbersĒ and it produces very difficult-to-maintain code.)
The class is called Month2 since thereís already a Month in the standard Java library. Itís a final class with a private constructor so no one can inherit from it or make any instances of it. The only instances are the final static ones created in the class itself: JAN, FEB, MAR, etc. These objects are also used in the array month, which lets you choose months by number instead of by name. (Notice the extra JAN in the array to provide an offset by one, so that December is month 12.) In main( ) you can see the type safety: m is a Month2 object so it can be assigned only to a Month2. The previous example Months.java provided only int values, so an int variable intended to represent a month could actually be given any integer value, which wasnít too safe.
This approach also allows you to use == or equals( ) interchangeably, as shown at the end of main( ).
Politica de confidentialitate|
Adauga cod HTML in site