java笔记 static关键字

一.static修饰变量和方法

在静态方法中不能访问非静态成员方法和非静态成员变量,但是在非静态成员方法中是可以访问静态成员方法/变量的
它不依附于任何对象,既然都没有对象,就谈不上this了

    package cn.bzu.look.dao;
    
    public class MyObject {
    
    
    	//非静态变量
    	private String str1 ="property";
    	//静态变量
    	private static String str2 ="staticProperty";
    	
    	public MyObject() {
    
    
    		
    	}
    	//非静态方法
    	public void print1() {
    
    
    		System.out.println(str1);
    		System.out.println(str2);
    		print2();
    	}
    	
    	//静态方法
    	public static  void print2() {
    
    
    		//这一句报错,报错信息是Cannot make a static reference to the non-static field str1
    		System.out.println(str1);
    		System.out.println(str2);
    		/*
    		 * 调用非静态的方法会报错,
    		 * Cannot make a static reference to the non-static method print1() from the type MyObject
    		 */
    		print1();
    	}
    }

在主类中,main就是被static所修饰的
如果这个时候我们在主函数外面定义一个非静态变量,主函数也是不能通过的

class text
{
    
    
    int x = 0 ;
    public static void main(String args[])
    {
    
    
        x = 1;   // 报错
        UniverStudent US = new UniverStudent(5053, "杨雨润", false);
    }
}

在这里插入图片描述

二.修饰只有一个版本的变量

    public class StaticTest {
    
    
    	static int value=33;
    	public static void main(String[] args) {
    
    
    		new StaticTest().print();
    	}
    	public void print() {
    
    
    		int value=3;
    		System.out.println(this.value);
    	}
    }

这里的答案输出是 33,this指向的是static int value=33,是自己类里面的value

猜你喜欢

转载自blog.csdn.net/yogur_father/article/details/108782031