java - static class explained

If you are from a C# background, you will know what I am talking about. In c# when a class is static, that means you cannot instantiate instance from this class. and beside, you cannot have instance method in the class definition. 

 

however, static class in java is a bit different, the static class is used in java as nested class, there is no such outer static class in java. 

 

so static class is in constrast to non-static nested class, where there is certain boundage from the nested class to its containing class. we will see an example below to show their difference. 

 

/** 
 * 
 * @author boqwang
 *
 * a note on the static class in Java
 * - C# interprets static classes as abstract final
 * - java class can be either abstract or final, not both. To Prevent a class from being instantiated, one can declare a private constructor.
 */


class OuterClass {
  public static class StaticNestedClass {
	  
  }
  
  public class InnerClass { 
	  
  }
  
  public InnerClass getAnInnerClass () { 
	  return new InnerClass();
	  // which is equivalent to 
	  // return this.new InnerClass();
  }
  
  public static StaticNestedClass getAnClassStatically() {
	  return new StaticNestedClass();
  }
  
  public static StaticNestedClass getAnInnerClassStatically() {
	  // this won't work, the instance to the OuterClass is needed.
	  // return new InnerClass();
	  return null;
  }
  
	
}


class OtherClass {
	// use of a static nested clas; - a static class can be used nested to an outer class, and which does not depends on the instance of the containing class.
	private OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();
	
	// this won't work,  you will need an instance of the outer class to make it work 
	// private OuterClass.InnerClass innerClass = new OuterClass.InnerClass(); 
	
	// use of inner class
	private OuterClass outerclass = new OuterClass();
	private OuterClass.InnerClass innerClass2 = outerclass.getAnInnerClass();
	
	// or you can do this way to explicitly create the Inner class instance 
	private OuterClass.InnerClass innerClass3 = outerclass.new InnerClass();
	
}

 

As you can see, 

 

  • C# interprets static classes as abstract final
  • Java can be either abstract or final, not both. To Prevent a class from being instantiated, one can declare a private constructor.

你可能感兴趣的:(java)