好程序员Java教程解密static关键字的理解

本文详细解析Java中的static关键字,包括其修饰属性、方法及代码块的不同应用场景,通过实例帮助理解static在类和对象间的调用机制。

好程序员Java教程分享static关键字的理解,static关键字含义可以理解为静态的。

1. 当其修饰属性时,该属性为整个类公有,所有的对象操作的都是同一个静态属性。所以调用时应该使用类名去调用,而不需要使用对象调用。


用类名去调用static有两层含义:

1. 可以理解为其为整个类公有的内容。

2. 可以理解为不需要创建对象就可以直接使用。


class  Student {

private  String name ;

private  String no ;

   // 此处省略掉getter和setter

public   static  String school ;


public   static   void  main(String[] args ) {

  Student stu1  = new  Student();

   stu1 . setName ( " 某某某 " );

   stu1 . setNo ( "1001" );

  Student. school  = "千锋" ;

  Student stu2  = new  Student();

  Student. school  = "千锋教育" ;

  System. out .println(Student. school );

}

}


2. 当其修饰方法时,该方法不需要对象调用,直接使用类名即可调用。


// 只显示代码片段

     public   static  String getSchool() {

       return   school ;

    }

    

     // 其他位置调用

    System. out .println(Student. getSchool ());


注意:在static方法中不能调用普通属性。也不能使用this关键字。因为static方法是使用类名调用的,而使用时不能判断是否创建对象,所以根本不能调用对象所对应的方法或属性,只能调用static的属性或方法。


    代码块,是指在类中,直接使用{}中间写一段代码,此代码不需要手动调用,在每次创建对象时会自动调用,甚至会在构造方法之前调用。


public   class  Student {

     private  String name ;

     private  String no ;

     public   static  String school ;

     public  Student(){

     System. out .println( "无参构造函数" );

     }

    

     {

     System. out .println( "此处是代码块" );

     }

}


3. 当static修饰代码块时,该代码块为静态代码块,在类加载时调用,仅在第一次加载时调用一次。不需要创建对象。如果创建了对象,调用次序为:先调用static代码块,再调用代码块,最后调用构造方法。


public   class  Student {

     private  String name ;

     private  String no ;

     public   static  String school ;

     public  Student(){

     System. out .println( "无参构造函数" );

     }

     {

     System. out .println( "此处是代码块" );

     }

     static {

     System. out .println( "此处是静态代码块" );

     }

}


当有一个父类Person,有一个子类Student,分别都有构造方法,代码块和静态代码块时,创建一个子类对象,调用次序为:


此处是Person静态代码块

此处是Student静态代码块

此处是Person代码块

Person无参构造函数

此处是Student代码块

Student无参构造函数


代码如下:


public   class  Person {

     public  Person(){

     System. out .println( "Person无参构造函数" );

     }

     {

     System. out .println( "此处是Person代码块" );

     }

     static {

     System. out .println( "此处是Person静态代码块" );

     }

 }


public   class  Student extends  Person{

     public  Student(){

     System. out .println( "Student无参构造函数" );

     }

    

     {

     System. out .println( "此处是Student代码块" );

     }

    

     static {

     System. out .println( "此处是Student静态代码块" );

     }

}


总结一句:static其实翻译类的,更容易理解,比如static修饰属性,称为类属性,static修饰方法,称为类方法。


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/69913892/viewspace-2651643/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/69913892/viewspace-2651643/

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值