Tuesday, February 3, 2009

Did you know: Static import

Static Import is a very simply and unnecessary opportunity in Java.

Static Import

The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members, either individually:

import static java.lang.Math.PI;
or:

import static java.lang.Math.*;

Once the static members have been imported, they may be used without qualification:

double r = cos(PI * theta);

It's easy and unnecessary as I said.

Monday, February 2, 2009

Protected Access Modifier Facts

I show an interesting example to the protected access modifier.



Our first file, Animal.java in package world:
01. package world;
02. public class Animal {
03. protected int age;
04. }


Our second file, Animal.java in package africa:
01. package africa;
02. import world.Animal;
03. public class Zebra extends Animal {
04. public void sayAge() {
05. System.out.println("My age is "+age); //Works well, age is protected;
06. }
07. public void sayFriendAge() {
08. Animal friend = new Animal();
09. System.out.println("My fried's age is " + friend.age ); //Compile error, age is accessible
10. // through inheritance
11. }
12. }


Our third file, Lion.java in package africa:
01. package africa;
02. public class Lion {
03. public void sayZebraAge() {
04. Zebra zebra = new Zebra();
05. System.out.println("Zebra's age is " + zebra.age ) ; //Compile error, Zebra and Lion are
06. // in the same package, but age is protected and only available using inheritance, Lion
07. // can't see it.
08. }
09. }