static关键字

static关键字
  • 作用:是一个修饰符,用于修饰成员(成员变量,成员方法)
  • 1、被static修饰后的成员变量只有一份
  • 2、当成员被static修饰后,多了一种访问方式,处理可以对象调用之外,还可以被类直接调用(类名. 静态成员)

static的特点:

  • 随着类的加载而被加载
  • 优先于对象的存在
  • 被所有对象所共享的
  • 可以直接被类名所调用

存放位置

  • 类变量随着类的加载而存在于data内存区
  • 实例变量随着对象的建立而存在于堆内存
public class test_static {
	public static void main(String[] args){
		Student6 A = new Student6();
		A.country = "中国";
		Student6 B = new Student6();
		System.out.println(B.country);
		System.out.println(Student6.country); //可以类名直接调用静态变量
	}
}

class Student6{
	String name;
	int age; //实例变量
	static String country; //静态变量(类变量)
}

在这里插入图片描述

静态方法
  • 静态方法只能访问静态成员
  • 非静态的方法既能访问静态的成员(成员变量,成员方法),也能访问非静态成员
  • 静态的方法中不可以定义this super 关键字,因为静态优先于对象存在,所以静态方法不可以出现this
public class test_static1 {
	public static void main(String[] args){
		whale3 A = new whale3();
		A.descrip();
		A.descrip1();
	}
}

class whale3{
	String name;
	static int age;
	static void descrip(){
		System.out.println(age);
	}
	static void descrip1(){
		String address = "冰岛"; //局部变量不能用static修饰
		System.out.println(address);
	}
}
什么时候使用静态成员
  • 当属同一个类的所有对象出现共享数据时,可以用static修饰这个成员变量
什么时候使用静态方法
  • 当功能内部没有访问到非静态的成员时(对象特有的数据),那么该功能可以定义成静态的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值