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

java,关键字static

时间:2017-02-22 00:04:46      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:unit   oid   ant   创建   string   str   div   ack   构造   

static:静态的,可以声明 字段,方法,和代码块[称为静态代码块],这样在一个 这个类的实例将可以共享他们[共产社会主义好]

  并且该类也可以直接使用它,无须实例化。和final一起使用时,被声明的字段为常量,必须初始化,且不能被修改,被声明的

  方法不能被重写。

package com.m01.teststatic;

import java.util.HashMap;
import java.util.Map;

public class Person {

    public Map map=null;
    public String name;
    public static int velt;
    public  static final int trunk=10;//常量,不可修改
    //trunk=12;
    public  static void eat(){
        Person p=new Person();
        System.out.println(p.velt);
    }
    public final static void drink(){
        Person p=new Person();
        System.out.println(p.velt);
    }
    public Person(){
        System.out.println("无参构造器");
    }
    public Person(int velt){
        this.velt=velt;
        System.out.println("有参构造器");
    }
    static{
        //map=new HashMap();
        Map map=new HashMap();
        System.out.println("静态代码块在实例化对象之前执行"
                + "可以创建对象,但是只能操作本类中的静态变量");
        velt=1;
        System.out.println("velt="+velt);
    }
}

测试

package com.m01.teststatic;
public class TestStatic {
    @org.junit.Test
    public void test(){
        Person p=new Person();
        System.out.println(p.velt);
        System.out.println(Person.velt);
        Person.velt=1;
        System.out.println(p.velt);
        System.out.println(Person.velt);
    }
    @org.junit.Test
    public void teststaticMethod(){
        Person p=new Person();
        p.eat();
        Person.eat();
    }
    @org.junit.Test
    public void teststaticBlock(){
        Person p=new Person(3);
        System.out.println(p.velt);
        System.out.println(Person.velt);
    }
    @org.junit.Test
    public void testConstant(){
        Person p=new Person(3);
        p.drink();
        Person.drink();
        System.out.println(p.trunk);
        System.out.println(Person.trunk);
    }
}

 

java,关键字static

标签:unit   oid   ant   创建   string   str   div   ack   构造   

原文地址:http://www.cnblogs.com/m01qiuping/p/6427021.html

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