static关键字

static原意是静态的,特殊的关键字。

java中的static关键字可作用在:变量、方法、类、匿名方法快。

静态变量是类的共有成员。

package mooc_6_1;

public class Potato {
	static int price=5;
	String content="";
	public Potato(int price,String content)
	{
		this.price=price;
		this.content=content;
	}

	public static void main(String[] args) {
		System.out.println(Potato.price);//不能输出Potatl.content,因为content不是静态变量,不是依赖于类的存在
		System.out.println("------------------");
		Potato obj1=new Potato(10,"青椒土豆丝");
		System.out.println(Potato.price);
		System.out.println(obj1.price);
	}

}

static变量只依赖于类存在(通过类即可访问),不依赖于对象实例存在,即通过Potato即可访问

所有的对象实例的值都共享在存储在一个共同的空间(栈)

static方法

静态方法也无需通过对象来引用,而通过类名就可以直接引用

在静态方法中,只能使用静态变量,不能使用非静态变量

静态方法禁止引用非静态方法(就好比如好学生可能主动跟差学生玩,但是差学生不会主动跟好学生玩)

非静态可以调用静态。

package mooc_6_1;

public class StaticMethodTest {
	int a = 111111;
	static int b = 222222;
	public static void hello() {
		System.out.println("000000");
		System.out.println("b");//静态方法调用静态变量;
		//System.out.println(a);// error,cannot call non-static variables
		/*调用的不是静态变量*/
		//hi()// error, cannot call non-static method,静态方法不能调用非静态方法;
	}
	public void hi() {
		System.out.println("333333");
		hello();//非静态方法可以调用静态方法;
		System.out.println(a);
		System.out.println(b);
	}
	public static void main(String[] a) {
		StaticMethodTest.hello();
		//StaticMethodTest.hi();error, 不能使用类名来调用非静态方法;
		StaticMethodTest foo = new StaticMethodTest();
		foo.hello();//可以用类名直接调用静态方法;
		foo.hi();
	}

}

 

总结:

startic变量:不管有多少个对象,内存中只有一份;

static方法:可以用类名直接引用,无需new对象来引用;

static块:static块只执行一次,并且static块(用的很少)》匿名块(用的很少)》构造函数(只需要知道顺序就行了)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值