码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-03-12 11:03:41      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:类变量   sys   static   ring   lin   return   ext   ati   ++   

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讲 类方法

标签:类变量   sys   static   ring   lin   return   ext   ati   ++   

原文地址:https://www.cnblogs.com/wangxiaoli/p/8547931.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!