1. 程式人生 > >韓順平 java筆記 第8講 this 類變量 第9講 類方法

韓順平 java筆記 第8講 this 類變量 第9講 類方法

post return lin pub color get tex 不能 join

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靜態變量,不能訪問非靜態變量,非靜態方法可以訪問靜態和非靜態變量。

韓順平 java筆記 第8講 this 類變量 第9講 類方法