java static关键字修饰方法

版权声明:尊重原创,码字不易,转载需博主同意。 https://blog.csdn.net/qq_34626097/article/details/83247417

1.java static关键字修饰方法的特性

  1. 随着类的加载而加载,在内存中也是独一份
  2. 可以直接通过“类.类方法”的方式调用
  3. 在静态的方法内部可以调用静态的属性或者静态的方法,而不能调用非静态的方法。反之,非静态的方法时可以调用静态属性或者方法的。
  4. demo
public class TestStatic {
	public static void main(String[] args) {
		SportsMan s1 = new SportsMan("金龙",23);

//		SportsMan.show();//因为这是一个普通的方法,所以不能通过类来调用
		s1.show();
		SportsMan.show1();
		s1.show1();
	}
}
class SportsMan{
	//实例变量(随着对象的创建而被加载的)
	String name;
	int age;
	//类变量
	static String nation;//出生是早于属性的
	
	public SportsMan(String name, int age) {
		super();
		this.name = name;
		this.age = age;
		this.nation = "China";
	}

	public void show() {
		System.out.println("nation:" + nation);
		info();
		System.out.println("age" + this.age);
		System.out.println("我是一名来自中国的运动员");
	}
	public static void show1() {
		System.out.println("nation:" + nation);
		info();
//		this.show();//报错,属性为非静态
//		System.out.println("age" + this.age);//报错,属性为非静态
		System.out.println("我是一名来自中国的运动员");
	}
	public static void info() {
		System.out.println("我是一个静态的方法!");
	}
}

2.注意要点

  1. 静态的结构(static的属性、方法、代码块、内部类)的生命周期要早于非静态的结构,同时被回收也要晚于非静态结构
  2. 静态的方法内是不可以有this或者super关键字的!

猜你喜欢

转载自blog.csdn.net/qq_34626097/article/details/83247417