static的出现,是方便在没有创建对象的情况下来进行调用,就是没有new 对象,而直接使用函数或者变量
- 静态不能访问非静态,但非静态可以访问静态
- 静态不能访问对象
一、static修饰函数
1、static在不同类的使用
public class student {
public void method() {
System.out.println("调用方法");
}
public static void methodStatic() {
System.out.println("调用静态方法");
}
}
public class demo1 {
public static void main(String[] args) {
student s = new student();
s.method();
s.methodStatic();//通过对象.函数使用
//student.method(); // 错误,非静态的函数,不能通过类.函数访问
student.methodStatic();//静态函数,通过通过类.函数使用
}
}
调用方法
调用静态方法
调用静态方法
可以看出,用了static修饰后,可以用类.方法来使用
2、static在同一个类中使用
public class demo1 {
public static void main(String[] args) {
test1();
demo1.test1();
//test2(); //错误
//demo1.test2(); //错误
demo1 d=new demo1();
d.test2();
}
public static void test1() {
System.out.println("本类的static函数");
}
public void test2() {
System.out.println("本类的非static函数");
}
}
本类的static函数
本类的static函数
本类的非static函数
在本类中,直接调用本类的函数,用了static后可以不用对象.函数
,也不用类.函数
,直接用函数使用就可以
3、静态不能访问非静态,但非静态可以访问静态
public class demo1 {
int num;
static int numStatic;
public void method() {
System.out.println("这是一个非static函数");
System.out.println(num);
System.out.println(numStatic);
System.out.println(this);
}
public static void methodStatic() {
System.out.println("这是一个static函数");
//System.out.println(num);//发生错误,因为这个是静态函数,静态函数不能访问非静态变量
System.err.println(numStatic);//静态函数可以访问静态变量
// System.out.println(this); //错误,因为静态不能访问对象,对象是有this的,类是没有this的
}
}
二、static修饰变量
当几个对象得某一个属性值是同一个值得时候,可以用static来进行简单的写代码
public class student {
int id;
String name;
static String classString;
public student(int id, String name) {
super();
this.id = id;
this.name = name;
}
}
public class demo1 {
public static void main(String[] args) {
student.classString = "17级1班";//一起赋值了
student s1 = new student(1, "小明");
student s2 = new student(2, "小兰");
System.out.println(s1.id + " ," + s1.name + " ," + s1.classString);
System.out.println(s2.id + " ," + s2.name + " ," + s2.classString);
}
}
1 ,小明 ,17级1班
2 ,小兰 ,17级1班
三、静态代码块
格式:
public class 类名称{
static{
//静态代码块
}
}
特点:
- 当第一次用到本类时,静态代码块执行唯一一次
- 静态优先于非静态
public class person {
public person() {
System.out.println("构造方法");
}
static {
System.out.println("静态代码块执行");
}
}
public class demo1 {
public static void main(String[] args) {
person p1 = new person();
person p2 = new person();
}
}
静态代码块执行
构造方法
构造方法