36

xiaoxiao2021-02-27  306

static关键字

在类中,用static声明的成员变量为静态变量(类变量)。

1.它为该类的公用变量,属于类,被该类的所有实例共享,在类被载入时被显式初始化。 2.对于该类的所有对象来说,static成员变量只有一份。被该类的所有对象共享!!3.可以使用”对象.类属性”来调用。不过,一般都是用“类名.类属性”。

4.用static声明的方法为静态方法: 不需要对象,就可以调用(类名.方法名) 在调用该方法时,不会将对象的引用传递给它,所以在static方法中不可访问非static的成员。

可以通过对象引用或类名(不需要实例化)访问静态成员。

非静态的变量和方法从属于对象,必须在创建对象后才能引用;静态的变量和方法从属于类,可通过类名.变量名、类名.方法名直接引用。 package cn.bjsxt.oop.testStatic; public class Student { String name; int id; static int ss; public static void printSS(){ System.out.println(ss); } public void study(){ printSS(); System.out.println(name+"在學習"); } public void sayHello(String sname){ System.out.println(name+"向"+sname+"說:你好!"); } } public class Test { public static void main(String[] args) { Student.ss = 323; Student.printSS(); Student s1 = new Student(); } }

内存分析:

转载请注明原文地址: https://www.6miu.com/read-7204.html

最新回复(0)