• 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);
        }
    }
  • 相关阅读:
    [转]在Ubuntu 下安装Redis 并使用init 脚本启动
    [资源]PHP使用消息队列
    [转]reids客户端 redis-cli用法
    [转]redis.conf的配置解析
    【转】微信公共号开发,提示“该公众号暂时无法提供服务,请稍后再试”,如何解决?
    [转]php 解决json_encode中文UNICODE转码问题
    [资料]Keychain 获取设备唯一
    [转]PHP 获取服务器详细信息代码
    crontab任务取消发送邮件
    [转]php返回json数据中文显示的问题
  • 原文地址:https://www.cnblogs.com/m01qiuping/p/6427021.html
Copyright © 2020-2023  润新知