首页 > 编程语言 > 详细

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

时间:2018-03-12 10:46:53      阅读:161      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!