Java Static Member Classes
Description
A static member class is a static member of an enclosing class. A static member class cannot access the enclosing class's instance fields and invoke its instance methods.
A static member can access the enclosing class's static fields and invoke its static methods including private fields and methods.
Example
The following code has a static member class declaration.
class Demo {/*w w w . j a v a2 s . c om*/
public static void main(String[] args) {
Main.EnclosedClass.accessEnclosingClass();
Main.EnclosedClass ec = new Main.EnclosedClass();
ec.accessEnclosingClass2();
}
}
class Main {
private static int outerVariable;
private static void privateStaticOuterMethod() {
System.out.println(outerVariable);
}
static void staticOuterMethod() {
EnclosedClass.accessEnclosingClass();
}
static class EnclosedClass {
static void accessEnclosingClass() {
outerVariable = 1;
privateStaticOuterMethod();
}
void accessEnclosingClass2() {
staticOuterMethod();
}
}
}
The static member classes can declare multiple implementations of their enclosing class.
Example 2
The following code declares a Rectangle
class and it uses static member class to
provide Rectangle
implementation for different data types, one is for double
type
and another is for float
type.
abstract class Rectangle {
abstract double getX();
/*ww w . ja va 2s . c om*/
abstract double getY();
abstract double getWidth();
abstract double getHeight();
static class Double extends Rectangle {
private double x, y, width, height;
Double(double x, double y, double width, double height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
double getX() {
return x;
}
double getY() {
return y;
}
double getWidth() {
return width;
}
double getHeight() {
return height;
}
}
static class Float extends Rectangle {
private float x, y, width, height;
Float(float x, float y, float width, float height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
double getX() {
return x;
}
double getY() {
return y;
}
double getWidth() {
return width;
}
double getHeight() {
return height;
}
}
private Rectangle() {
}
boolean contains(double x, double y) {
return (x >= getX() && x < getX() + getWidth()) && (y >= getY() && y < getY() + getHeight());
}
}
public class Main {
public static void main(String[] args) {
Rectangle r = new Rectangle.Double(10.0, 10.0, 20.0, 30.0);
r = new Rectangle.Float(10.0f, 10.0f, 20.0f, 30.0f);
}
}