Core Java (七) Java中的static修饰符



From:http://blog.csdn.net/xujinsmile/article/details/8523251


static为静态的意思,常用来修饰内部类,方法,变量。


静态域

static修饰的变量在每个类中只有一个副本,即这个类的所有对象共享一个变量,它属于类,不属于任何独立的对象。

[java]  view plain  copy
  1. package com.xujin;  
  2.   
  3. class Base{  
  4.     protected static int MAX = 100;  
  5. }  
  6.   
  7. public class Another extends Base{  
  8.     public static void main(String[] args){  
  9.         Base base1 = new Base();  
  10.         Base base2 = new Base();  
  11.         Base base3 = new Base();  
  12.         System.out.println(base1.MAX);//100  
  13.         System.out.println(base2.MAX);//100  
  14.         System.out.println(base3.MAX);//100  
  15.         base1.MAX = 10;  
  16.         System.out.println(base1.MAX);//10  
  17.         System.out.println(base2.MAX);//10  
  18.         System.out.println(base3.MAX);//10  
  19.     }  
  20. }  


静态常量

static final 修饰符,即为常量。

[java]  view plain  copy
  1. public class Math{  
  2.         ...  
  3.         public static final PI = 3.14159265358979323846;  
  4.         ...  
  5.     }  

Math.PI就可以访问该常量。

public static final 修饰符很重要,他可以公开给别的类但不允许其他类修改。



静态方法

static方法是静态方法,是一种不能向对象实施操作的方法(即没有隐式的参数this),比如Math.random(),Math.pow(x, a);  

不能在一个static方法内部访问非static变量,可以通过类名(推荐)和对象名(不推荐)调用这个方法。

静态方法不能被重写,一个非static(普通的)方法也不能在子类中重写为static 方法。另外,一个static方法也不能在子类中重写为static 方法中,因为重写必须符合多态性,而static并不符合这个规定。

如下例子:

[java]  view plain  copy
  1. package com.xujin;  
  2.   
  3. class Base{  
  4.     public static void aMethod(){  
  5.         System.out.println("Base a");  
  6.     }  
  7.     public void bMethod(){  
  8.         System.out.println("Base b");  
  9.     }  
  10. }  
  11.   
  12. public class Another extends Base{  
  13.     public static void main(String argv[]){  
  14.         Base so = new Another();  
  15.         Another fo = new Another();  
  16.           
  17.         so.aMethod();//Base a         
  18.         fo.aMethod();//Another a  
  19.           
  20.         so.bMethod();//Another b  
  21.         fo.bMethod();//Another b  
  22.           
  23.     }  
  24.     public static void aMethod(){  
  25.         System.out.println("Another a");  
  26.     }     
  27.     public void bMethod(){  
  28.         System.out.println("Another b");  
  29.     }     
  30. }  

其中有一个静态方法aMethod()和一个非静态方法bMethod(),bMethod()符合多态性,而静态方法aMethod()不符合多态性。

所以说这个不属于方法重写。



main方法

当启动程序的时候还没有任何一个对象,所以静态的main方法将执行并创建程序所需要的对象。

main方法也可以用来对某个类进行单元测试。



静态内部类

把一个类隐藏在另一个类的内部,内部类不可引用外部类对象,取消了产生的引用。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值