Newsletter sign-up
View all newsletters

Sign up for our technology specific newsletters.

Enterprise Java
Email Address:

Static class declarations

Can a class -- inner or outer -- be declared static?

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

Page 2 of 2

If your main class has a few smaller helper classes that can be used outside the class and make sense only with your main class, it's a good idea to make them nested top-level classes. To use the nested top-level class, write: TopLevelClass.NestedClass.

See the following example:

public class Filter {
   Vector criteria = new Vector();
   public addCriterion(Criterion c) {
      criteria.addElement(c);
   }
   public boolean isTrue(Record rec) {
      for(Enumeration e=criteria.elements();
      e.hasMoreElements();) {
         if(! ((Criterion)e.nextElement()).isTrue(rec))
             return false;
      }
      return true;
   }
   public static class Criterion {
      String colName, colValue;
      public Criterion(Stirng name, String val) {
         colName = name; colValue = val;
      }
      public boolean isTrue(Record rec) {
         String data = rec.getData(colName);
         if(data.equals(colValue)) return true;
         return false;
      }
   }
}


And when you want to use it:

Filter f = new Filter();
f.addCriterion(new Filter.Criterion("SYMBOL", "SUNW"));
f.addCriterion(new Filter.Criterion("SIDE", "BUY"));
.....
if(f.isTrue(someRec)) //do some thing .....


One important note: The static keyword does not do to a class declaration what it does to a variable or a method declaration.

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comments (15)
Login
Forgot your account info?

Inner class object creation in mainBy Anonymous on November 16, 2009, 2:44 pmIs it necessary to declare an inner class as static if we want to create its object in main which is in same outer class??

Reply | Read entire comment

No ref to parentBy Anonymous on October 20, 2009, 4:03 amYou could declare all the inner classes without a reference to the parent object to be static inner classes.

Reply | Read entire comment

static classBy Anonymous on September 19, 2009, 11:15 pmIs that required create an instance to static class explicitly....?

Reply | Read entire comment

shall we have all static methods in class then wht we call that By Anonymous on August 21, 2009, 1:39 amShall we have all static methods in a class then what is that class called ? could you please explain me

Reply | Read entire comment

Was of great help to me, in understanding why the inner classes By Anonymous on August 17, 2009, 11:18 amWas of great help to me, in understanding why the inner classes are declared static. Thanks

Reply | Read entire comment

View all comments

Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources