A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© panbingqi 中级黑马   /  2015-4-21 19:36  /  495 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/*
static关键字注意事项
  在静态方法中是没有this关键字的
   对象创建完毕后,有了this 对象
   没有没有创建对象,没有 this 对象
   所以说,this代表当前对象的引用
  注意: 静态的方法加载进来的时候,这个时候对象还没有创建呢,
    对象都没创建,哪来的this呢? 所以不行
  静态方法只能访问静态的成员变量和静态的成员方法
   普通方法:
     变量:访问普通的变量和 静态变量
     方法:访问普通方法和静态方法
   静态方法:
     变量:访问静态变量
     方法:访问静态方法
   一句话: 静态只能访问静态
*/
class Student {
String name = "赵日天";
int age = 30;
static String country = "中国";

//普通
public void method(){
  //普通变量
  System.out.println(name +"---"+age);
  //静态变量
  System.out.println(country);
  //System.out.println(this.name +"---"+this.age);

  //调用方法
  method2();
  function2();
}
//静态方法
public static void function(){
  //普通变量
  //System.out.println(name +"---"+age);
  //System.out.println(this.name +"---"+this.age);
  //静态变量
  System.out.println(country);
  //访问普通方法
  //method2();//错误: 无法从静态上下文中引用非静态 方法 method2()
  //访问静态方法
  function2();
}
//普通方法
public void method2(){}
//静态方法
public static void function2(){}
}
class StudentDemo {
public static void main(String[] args) {
  //创建对象
  Student s = new Student();
  s.method();
}
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马