温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中static关键字的介绍和用法

发布时间:2021-09-04 23:11:43 来源:亿速云 阅读:110 作者:chen 栏目:编程语言

本篇内容主要讲解“Java中static关键字的介绍和用法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Java中static关键字的介绍和用法”吧!

用类名去调用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修饰方法,称为类方法。

到此,相信大家对“Java中static关键字的介绍和用法”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI