Java基础入门-java中的static使用

Java中被static修饰的成员称为静态成员。它属于整个类所有,而不是某个对象私有;静态成员可以用类名直接访问或者使用对象名访问。


静态变量  使用static修饰的变量称为静态变量

package com.demo.test;

public class Demo1 {
	//static 修饰的变量称为静态变量,所有类的对象共享
	static String name = "abcdefg";
	public static void main(String[] args){
		//静态变量可以直接使用类名来访问,无需创建类的对象
		System.out.println("通过类名访问name:" + Demo1.name);
		
		//通过创建对象来访问
		Demo1 demo1 = new Demo1();
		System.out.println("通过对象来访问name:" + demo1.name);
		
	}
}
输出结果:
通过类名访问name:abcdefg
通过对象来访问name:abcdefg

静态方法  使用static修饰的方法称为静态方法

package com.demo.test;

public class Demo1 {
	int china = 67;
	static int math = 92;
	//计算总成绩
	public static int score(){
		Demo1 demo1 = new Demo1();
		return demo1.china + math;
	}
	
	public static void main(String[] args){
		//方法一
		Demo1 demo2 = new  Demo1();
		int SumScore = demo2.score();
		System.out.println("方法一总分:"+SumScore);
		
		//方法二
		int SumScore2 = score();
		System.out.println("方法二总分:"+SumScore2);
	}
}

注意:

1.静态方法中可以直接调用同类中的静态成员,但是不能直接调用非静态成员;

如果希望在静态方法中调用非静态变量,可以通过创建对象,然后通过对象来访问非静态变量。例如

<pre name="code" class="java">public class Demo1 {
	String a ;
	static String b ;
	public static void main(String[] args){
		Demo1 demo1 = new Demo1();
		System.out.println(demo1.a);
		System.out.println(b);
	}
}
 

 
2 
.在普通成员方法中,则可以通过直接访问同类的非静态变量和静态变量 

public class Demo1 {
	int china = 67;
	static int math = 92;
	public int score(){
		return china + math;
	}
}
3.静态方法中不能直接调用非静态方法,需要通过对象来访问非静态方法
package com.demo.test;

public class Demo1 {
	int china = 67;
	static int math = 92;
	public int score1(){
		return china + math;
	}
	
	public static void main(String[] args){
		Demo1 demo2 = new  Demo1();
		int SumScore = demo2.score1();
		System.out.println("总分:"+SumScore);
	}
}

静态初始化快

package com.demo.test;

public class Demo1 {
	String a ;
	String b ;
	static String c ;
	static int count =0 ;
	//构造方法
	public Demo1(){
		++count;
		a = "a";
		System.out.println("这是通过构造方法为a赋值,这是第"+count+"步执行");
	}
	//初始化块
	{
		++count;
		b = "b";
		System.out.println("这是初始化块为b赋值,这是第"+count+"步执行");
	}
	//静态初始化块
	static{
		++count;
		c = "c";
		System.out.println("这是静态初始化块为c赋值,这是第"+count+"步执行");
	}
	
	public static void main(String[] args){
		Demo1 demo1 = new Demo1();
		System.out.println("a:"+demo1.a);
		System.out.println("b:"+demo1.b);
		System.out.println("c:"+demo1.c);
		Demo1 demo2 = new Demo1();	
	}
}<strong>
</strong>
运行结果:
这是静态初始化块为c赋值,这是第1步执行
这是初始化块为b赋值,这是第2步执行
这是通过构造方法为a赋值,这是第3步执行
a:a
b:b
c:c
这是初始化块为b赋值,这是第4步执行
这是通过构造方法为a赋值,这是第5步执行


通过输出的结果,我们可以看到,程序运行的时候,静态初始化代码块最先执行,然后是普通的初始化代码块,最后是构造方法。

由于静态初始化块只在累加载一次,所以在第二次创建对象demo2的时候,并没有执行静态初始化块




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值