java - static class explained

本文对比了Java和C#中的静态类概念,解释了两者在类的实例化、构造函数以及抽象和最终类的区别,并通过代码示例展示了它们在不同场景下的应用差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值