zoukankan      html  css  js  c++  java
  • static关键字的使用

    static关键字的使用:
    * 1.static:静态的
    *
    * 2.static可以用来修饰:属性、方法、代码块、内部类。
    *
    * 3. 使用static修饰属性:类变量(或静态变量
    * >使用static修饰的变量,被类的所对象所共享:类的所对象共同同一个静态变量。
    * 对比:不用static修饰的属性,称为:实例变量。每个对象拥一份实例变量。通过对象a修改某个实例变量,
    * 不会影响其他对象同名的实例变量的值。
    * >我们可以通过对象a去调用或修改静态变量的值,那么会影响其他对象对此静态变量的调用。
    * >静态变量和实例变量在内存中分配的位置不同:
    * 实例变量,随着对象的创建而产生,分配在堆空间中。
    * 静态变量,随着类的加载而产生的,分配在方法区。
    * >静态变量的加载要早于对象的创建。
    * > 静态变量 非静态变量(实例变量
    * 类 可以 不可以
    * 对象 可以 可以
    *
    * 4. 使用static修饰方法:静态方法
    * >随着类的加载而加载
    * > 静态方法 非静态方法
    * 类 可以 不可以
    * 对象 可以 可以
    * >静态方法内:可以调用静态的属性或静态的方法。不可以调用非静态的属性和非静态的方法。
    * 非静态的方法内:可以调用非静态的属性和非静态的方法。也可以调用静态的属性或静态的方法。
    *
    * 5. 如何判定属性是否需要声明为static的?是否需要类的多个对象来共享此属性;很多常量都声明为static的
    *
    * 如何判定方法是否需要声明为static的?操作静态变量的方法;工具类中的方法。(Math.random();)
    * public class StaticTest {

    public static void method(){

    }

    public static void main(String[] args) {


    Chinese c1 = new Chinese();
    c1.name = "孙杨";
    c1.age = 20;
    c1.nation = "CHN";
    System.out.println(c1);

    Chinese c2 = new Chinese();
    c2.name = "姚明";
    c2.age = 35;
    //c2.nation = "CHN";
    c2.nation = "中国";
    System.out.println(c2);
    System.out.println(c1);

    System.out.println(Chinese.nation);
    // System.out.println(Chinese.name);
    System.out.println(Math.PI);

    c1.show();
    Chinese.show();

    // System.out.println(Chinese.toString());


    System.out.println();

    // StaticTest t = new StaticTest();
    // t.method();

    // method();
    }
    }

    class Chinese{
    String name;
    int age;
    static String nation;
    @Override
    public String toString() {
    return "Chinese [name=" + name + ", age=" + age + ", nation=" + nation + "]";
    }


    public static void show(){
    System.out.println("我是一个中国人!");
    Chinese.info();
    System.out.println("nation = " + nation);
    // this.display();
    // System.out.println("name = " + name);
    }

    public static void info(){
    System.out.println("合唱“中国人”");
    }
    //非static的方法
    public void display(){
    System.out.println("我叫" + name + ",今年" + age + "岁");
    //静态结构:
    info();
    System.out.println("nation = " + nation);
    }

    }

  • 相关阅读:
    JSP
    Tomcat根据JSP生成Servlet机制解析
    JSON基础
    ATouch 吃鸡开发板原理及功能介绍
    Android触摸touchevent的AB两种方式(TYPE_A,TYPE_B)识别方法
    ubuntu诸软件安装
    linux kernel mini2440 start.S head-common.S 部分注释
    Android USB ADB ATUH 验证包验证流程
    USB协议学习
    Android memory dump
  • 原文地址:https://www.cnblogs.com/loushiqiang/p/7252932.html
Copyright © 2011-2022 走看看