java static 静态属性

来源:互联网 发布:vue.js ajax 编辑:程序博客网 时间:2024/04/29 19:55
static 属于全局,也就是类的属性 和方法,换句话说 一个类,不管有多少个实例,却只有一个全局变量  class person{static int age=9;static String name="hello";public void print(){
  System.out.println("他的年龄:"+a+"\n"+"他的姓名:"+b);
}}

public class PersonOne{

public static void main(String args[]){

Person per1=new Person();.//实例化Person对象,也叫person类;

Person per2=new Person();.//实例化Person对象,也叫person类;

           per1.print();//调用类方法;output输出信息;

          per2.print();//调用类方法;output输出信息;

都是类B的实例,每个实例都共享 变量age,name,是全局变量,属于类Person的属性,每个实例都能引用变量age,name, static 方法也是类似的

需要注意的是 静态属性和方法属于类方法,加载类后,就已经存在静态属性和方法,实例是需要用new构造出来后 才会有引用

根据先后顺序,就有以下两条规则

1、非静态的方法可以调用静态的或者非静态的属性和方法;

 2、静态的方法不可以调用非静态的属性和方法,因为非静态的还不一定存在,只能先构造出来后,再通过实例引用

例如 在main方法中 可以直接调用static 的方法,调用非static方法 需要先构造出类的实例,通过实例才能调用方法

static修饰变量只能是class的成员变量,而不能是方法内的变量      
static 修饰方法就是说不需要实例化就可以调用该方法    譬如  class Person{       public static void StaticPrint(){ System.out.println("hello,may,wellcome to http://jinziyangfushi.taobao.com"}    public void nonStaticPrint(){               System.out.println("Say.the price is weak");
}    }    public class PersonDemo{
public static void main(String args[]){
//对于staticPrint,
//可以直接这样写
A.staticPrint()..  对nonStaticPrint(){},则必须是  Person per  =new Person()  a.nonStaticPrint()  
                                             
0 0