韩顺平 java笔记 第8讲 this 类变量 第9讲 类方法

时间:2022-10-17 21:04:11

1.类变量 即static

  public class Demo{

    public static void main(String[] args){

      Child ch1 = new Child(3,"妞妞");

      ch1.joinGame();

      Child ch2 = new Child(4,"小小");

      ch2.joinGame();   

      Child ch3 = new Child(5,"大大");

      ch3.joinGame();

      System.out.println("共有="+Child.total);

    }

  }

  class Child{

    int age;

    String name;

    static int total=0;

    public Child(int age,String name){

      this.age=age;

      this.name=name;

    }

    public void joinGame(){

      total++;

    }

  }

 

2.类方法

   public  class Demo{

    public static void main(String[] args){

      Stu stu1 = new Stu(29,"aa",340);

      Stu stu2 = new Stu(29,"bb",240);

      System.out.println(Stu.getTotalFee());

    }

  }

  class Stu{

    int age;

    String name;

    int fee;

    static int totalFee;

    public Stu(int age,String name,int fee){

      this.age = age;

      this.name = name;

      totalFee+=fee;

    }

    public static int getTotalFee(){//这是一个静态方法

      return totalFee;

      age ++;//错的,

    }

  }

***static静态方法可以访问static静态变量,不能访问非静态变量,非静态方法可以访问静态和非静态变量。