温馨提示×

温馨提示×

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

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

JAVA类变量及类方法代码实例详解

发布时间:2020-10-03 22:39:02 来源:脚本之家 阅读:111 作者:白客C 栏目:编程语言

这篇文章主要介绍了JAVA类变量及类方法代码实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

类变量(static)

类变量是该类的所有对象共享的变量,任何一个该类的对象去访问它时,取到的都是相同的值,同样任何一个该类的对象去修改它时,修改的也是同一个变量。

public class C {
  public static void main(String[] args){

    Child ch2 = new Child(12,"小小");
    ch2.joinGame();
    Child ch3 = new Child(13,"小红");
    ch3.joinGame();
    //调用类变量
    System.out.println("一共有" + Child.total+ "小朋友");
  }
}

class Child{
  public int age;
  public String name;

  //total是静态变量,因此他可以被任何类调用
  public static int total = 0;

  public Child(int age, String name)
  {
    this.age = age;
    this.name = name;
  }

  public void joinGame()
  {
    total++;
    System.out.println("有一个小朋友加进来!");
  }
}

运行结果

JAVA类变量及类方法代码实例详解

静态区块

只要程序启动就会被执行一次,也仅执行一次

public class C {

  static int i = 1;
  static
  {
    System.out.println("静态区域块被执行一次");
    //该静态区域块,只被执行一次,也不会因创建对象而触发
    i++;
  }
  public C()
  {
    System.out.println("构造函数域块被执行一次");
    i++;
  }

  public static void main(String[] args){

    C t1 = new C();
    System.out.println("输出第一个i的值为:" + C.i);
    C t2 = new C();
    System.out.println("输出第二个i的值为:" + C.i);
  }
}

运行结果

JAVA类变量及类方法代码实例详解

类方法

类方法中不能访问非静态变量

public class C {
  public static void main(String[] args){
    Student stu1 = new Student(18,"小红",580);
    Student stu2 = new Student(18,"小黑",620);
    System.out.println("有" + Student.p_total + "个学生");
    System.out.println("学费总收入:" + Student.get_total_fee());
  }
}

//定义一个学生类
class Student{
  public int age;
  public String name;
  public double fee; //学费
  public static int p_total = 0;
  public static double total_fee; //总学费

  public Student(int age, String name, double fee)
  {
    p_total++;
    this.age = age;
    this.name = name;
    this.total_fee += fee;
  }

  //静态方法
  //Java中规则:类变量原则上用类方法去访问
  public static double get_total_fee()
  {
    return total_fee;
  }
}

运行结果

JAVA类变量及类方法代码实例详解

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

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

AI