Sunday, November 13, 2011

Enum constructor visibility

Tip: The constructor for an enum type must be package-private or private access.

We will validate this by defining Enum with public constructor and see what happens:

enum Color {

 RED, BLUE, YELLOW;

 public Color() {

  System.out.println("Color");

 }}

As you can test, this code will fail to compile.

Now let's remove the public modifier from constructor or replace it with private modifier:

enum Color {

 RED, BLUE, YELLOW;

 Color() {

  System.out.println("Color");

 }}

This time it compiles and proves today's tip. 

Available in Android Market

Friday, November 11, 2011

Static member classes and instance variables.

Tip: Static member class doesn't have access to non static members of outer class.

Like always, let's test it with a small code snippet:

public class Dolls {
    public int dollCount = 25;
    public static class Barbie{
        void printVar () {
            System.out.println(dollCount);
        }
    }
    public static void main(String[] args) {
        Dolls.Barbie barbie = new Dolls.Barbie();
        barbie.printVar();
    }
}

We have defined a top level class Dolls with static member class Barbie and member variable dollCount. Within Barbie we have used dollCount. 

If you try to run this example you will get a compilation error where dollCount is referenced within Barbie. 

Compilation error validates today's tip. 

Available in Android Market

Thursday, November 10, 2011

Primitive type long as Array index


Tip: Using a long index value to access an array causes a compilation error.

Let's try it with small piece of code.

public class TestArray {

 public static void main(String[] args) {

  int [] a = {1, 2, 3};

  long i = 1;

  System.out.println(a[i]);

 }}

If you try to compile and run above code, you will get following compile time exception:

Type mismatch: cannot convert from long to int.

Use SCJP Champ to learn Java The Fun Way!
Available in Android Market

Wednesday, November 9, 2011

Can constructors throw exception

Tip: Java constructors can throw Exceptions. The throws clause for a constructor is identical in structure and behavior to the clause for a method.

Let's try to put some code:
class Foo {


    Foo () throws FileNotFoundException {

    }

    public static void main(String[] args) {
        try {
            Foo foo = new Foo();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
Above code will compile and run perfectly.

Use SCJP Champ to learn Java The Fun Way!
Available in Android Market