zoukankan      html  css  js  c++  java
  • java,关键字static

    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);
        }
    }
  • 相关阅读:
    致初学作曲的业余音乐爱好者 (转载)
    OpenGL教程 "Top Ten" (转载)
    开发者:我们应该在哪个层次编写代码?
    计算机科学数学理论浅谈 (转载)
    fltk2更新简介
    搜集的优良OpenGL教程 (转载)
    [转载] 跨平台C++程序开发系列文章
    通过HtppWebRequest发送图片到服务器并保存
    技术之外
    Hibernate写查询语句注意事项
  • 原文地址:https://www.cnblogs.com/m01qiuping/p/6427021.html
Copyright © 2011-2022 走看看