Monday, November 16, 2009

SCJP 1.6 Study Guide: Declarations and Access Controls Part 9

Declaring Arrays, Enums and Methods with Variable Argument Lists (var-args)

This is the last part for the Declarations and Access Controls section. If you missed most of the parts of this section please go to the table of contents for this study guide series.

Methods with Variable Argument Lists. Variable argument lists or var-args has been available since Java 5.0. For now, let's focus on declaring var-args. Here are the rules in using var-args:
  • Just like declaring a regular method parameter, you must specify the type that your var-args will accept. This type maybe primitive or an object type.
  • To declare a var-args parameter you must follow the type immediately with an ellipsis(...), a space and then the name of the parameter.
  • It is legal to have other parameters in the method declaration, but there can be only one var-args parameter and it should be the last parameter.
Example Legal:
int addNumbers(int... numbers){}
void storeInformation(String s, int... x){}
void addContacts(String... contacts){}
Example Illegal:
int addNumbers(int numbers...){}
void storeInformation(int... x, String x){}
Declaring Arrays. Arrays are objects that can store multiple variables of the same type or subtypes(polymorphism). Arrays can hold either primitive variables or reference variables. An array is also an object, even if it is declared to hold primitives. For the exam you need to know how to declare arrays, construct arrays and initialize arrays, however, we will focus on declaring arrays first and discuss the remaining two later.

Just like variables arrays are declared by declaring the type of variables it will hold and a pair of square bracket after the type or after the variable name. It is recommended to put the square brackets right after the type and before the variable name for better readability.

Example:
int[] numbers; // recommended

int numbers[]; // legal

String[] names;

String names[];
You can also declare multidimensional arrays, which are simply arrays of arrays.

Example:
int[][] numbers; // two dimensional

String[][] names[]; // three dimensional
If you notice the names array has two square brackets after the type and one after the variable name. This is legal but not recommended.

Declaring Enums. Enums or items in an enumerated list was made available since Java 5.0. Emuns allows you to restrict a variable's value to just one of a predefined list of enumerated values.

Example:
enum ShirtSize {SMALL, MEDIUM, LARGE}; // this cannot be private or protected
In the example above, we've declared an enum ShirtSize so if we want to set a Shirt to be of small size then we just do this:

Example:
public class Shirt{
ShirtSize size;

public static void main(){
Shirt shirt = new Shirt();
shirt.size = ShirtSize.SMALL;
}
}
The basic component of an enum is its constants, so the declaration of ShirtSize is the barebones declaration of an enum, and you still can add other declarations.As you may have observed the enum constants are all in uppercase, this is not a requirement but just another area where we use Sun's naming convention for constants.

Enums can be declared separate from other classes(example) or within a class as a member but not inside any method.

Example:
public class Shirt{
enum ShirtSize {SMALL, MEDIUM, LARGE};

ShirtSize size;

public static void main(){
Shirt shirt = new Shirt();
shirt.size = Shirt.ShirtSize.SMALL; // enclosing class is required
}
}
Furthermore, it is also legal to omit the semi-colon after the enum declaration as it is optional.

Example:
public class Shirt{
enum ShirtSize {SMALL, MEDIUM, LARGE}

ShirtSize size;

public static void main(){
Shirt shirt = new Shirt();
shirt.size = Shirt.ShirtSize.SMALL;
}
}
Enum constants are not types like primitive types and reference types. The enum constants are different instances of the enum where it is declared. Take a look at the ff for a theoretical perspective of an enum:

Example:
public class ShirtSize{
public static final ShirtSize SMALL = new ShirtSize("S");
public static final ShirtSize MEDIUM = new ShirtSize("M");
public static final ShirtSize LARGE = new ShirtSize("L");
}
Each enum constant in an enum has its corresponding index which is determined by the order in which they are declared. So in our previous ShirtSize example SMALL has an index of 0, MEDIUM(1) and LARGE(2).

Enum Constructors, Methods and Variables Declaration. Since an enum is a special kind of class you can add constructors, instance variables and methods to its constants. You can also add what we call a constant specific class body.

So we've declared the enum ShirtSize with SMALL, MEDIUM and LARGE constants but how do we know or set the real values of the sizes? Simply by passing a value to a constructor of the enum.

Example:
enum ShirtSize{
SMALL(28), MEDIUM(32), LARGE(36);

ShirtSize(int inches){ // constructor
this.inches = inches;
}

private int inches;

public int getInches(){
return inches;
}
}
public class Shirt{
private ShirtSize size;

public void setSize(ShirtSize size){
this.size = size;
}

public ShirtSize getSize(){
return size;
}
}
public class TestShirt{
public static void main(String[] args){
Shirt shirt = new Shirt();
shirt.setSize(ShirtSize.SMALL);
System.out.println(shirt.getSize() + " " + shirt.getSize().getInches());
shirt.setSize(ShirtSize.MEDIUM);
System.out.println(shirt.getSize() + " " + shirt.getSize().getInches());
shirt.setSize(ShirtSize.LARGE);
System.out.println(shirt.getSize() + " " + shirt.getSize().getInches());
}
}
Which prints:
SMALL 28
MEDIUM 32
LARGE 36
Note that to get all the constants of an enum you just have to call the values() method (i.e. ShirtSize.values()) which returns an array representation of the constants arranged in the order they were declared.

Things to remember about enum constructors:
  • You can never invoke an enum constructor directly. It is invoked automatically.
  • You can define several arguments in an enum constructor just like a regular class. We will discuss overloading in the next section.
Constant Specific Class Body. This is used when you want to override a method in an enum for a particular constant. For example, you want to have the default price for all the sizes except for LARGE to be 300. So you define a method to set the price to 300 and override that method in LARGE to give it a different value.

Example:
enum ShirtSize{
SMALL(28),
MEDIUM(32),
LARGE(36){ // code block that defines the body for this constant
public int getPrice(){ // override the getPrice() method of ShirtSize
return 500;
}
}; // semi-colon is required to end the constant body
// when more codes follow

ShirtSize(int inches){ // constructor
this.inches = inches;
}

private int inches;

public int getInches(){
return inches;
}

public int getPrice(){
return 300;
}
}
public class TestShirt{
public static void main(String[] args){
Shirt shirt = new Shirt();
shirt.setSize(ShirtSize.SMALL);
System.out.println(shirt.getSize() + " " + shirt.getSize().getPrice());
shirt.setSize(ShirtSize.MEDIUM);
System.out.println(shirt.getSize() + " " + shirt.getSize().getPrice());
shirt.setSize(ShirtSize.LARGE);
System.out.println(shirt.getSize() + " " + shirt.getSize().getPrice());
}
}
Which prints:
SMALL 300
MEDIUM 300
LARGE 500
This post ends the Declarations and Access Controls section. Next section will be Object Orientation.

0 comments:

Post a Comment