036_面向对象_09_static变量和方法

一、概念部分

  静态变量:在类中,用static声明的成员变量为静态变量(也叫类变量、类属性)。

二、静态变量的特点  

  1.它为该类的公用变量,属于类,被该类的所有实例共享,在类被载入时被显式初始化

  2.对于该类的所有对象来说,static成员变量只有一份。被该类的所有对象共享

  3.可以使用”对象.类属性”来调用。不过,一般都是用“类名.类属性”。

  4.用static声明的方法为静态方法,静态方法中不可以调用非静态方法和属性,而非静态方法中可以调用静态属性或静态方法。

  5.不需要对象,就可以调用(类名.方法名)

三、演示示例  

package test;
/**
 * [说明]测试静态属性和静态方法
 * @author aeon
 *
 */
public class Student {
    String name;
    int id;
    static int ss;

    public static void printSS() {
        //id=3;静态方法中不可以调用非静态方法和属性
        System.out.println(ss);
    }

    public void study() {
        /**
         *普通方法中可以使用静态属性或静态方法
         */
        id=3;
        printSS();
        System.out.println(name + "在学习");
    }

    public void sayHello(String sname) {
        System.out.println(name + "向" + sname + "说:你好!");
    }

    public static void main(String[] args) {
        Student.ss = 323;
        Student.printSS();
        Student s1 = new Student();
    }
}

以上代码内存图:

  

猜你喜欢

转载自www.cnblogs.com/aeon/p/9958011.html