Java关键字——static

static申明属性

如果有属性希望被所有对象共享,则必须将其申明为static属性。

使用static声明属性,则此属性称为全局属性,有时候也称为静态属性。

当一个类的属性申明为static的时候,由这个类产生的多个对象中属性,只需要对其中一个对象的该属性进行修改,即可以修改所有对象的这个属性

若只申明为public,没有static的时候,则修改申明的对象的属性只修改一个,申明为private的时候报错,因为该属性私有化,不能被方法所调用。

在调用static申明的属性的时候,最好通过类名称来直接调用,因为通过对象来调用不知道该类产生了多少的对象,这样子不太好,所以又把static声明的属性称为类属性,调用的格式位Person_1.coountry="B city";

class Person_1{
	private String name;
	private int age;
	static String country = "A city";
	
	public Person_1(String n,int a){
		this.name = n;
		this.age = a;
	}
	
	public void info(){
		System.out.println("name:"+this.name+"	"+"age:"+this.age+"	"+"city:"+this.country);
	}
};


public class static_test {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Person_1 p1 = new Person_1("zhangsan",30);
		Person_1 p2 = new Person_1("wangwu",40);
		p1.info();
		p2.info();
		p1.country = "B city";
		p1.info();
		p2.info();
	}

}

输出

name:zhangsan	age:30	city:A city
name:wangwu	age:40	city:A city
name:zhangsan	age:30	city:B city
name:wangwu	age:40	city:B city

Java中的常用的内存区域

  <1>栈内存空间:保存所有的对象名称(更准确的说是保存了引用的堆内存空间的地址)

  <2>堆内存空间:保存每个对象的具体属性内容

  <3>全局数据区:保存static类型的属性

  <4>全局代码区:保存所有的方法定义

Java其他关键字

public:表示此方法可以被外部调用

static:表示此方法可以由类名称直接调用

void:主方法是程序的起点,所以不需要任何的返回值

main:系统规定好默认调用的方法名称,执行时默认找到main方法名称

String arg[]:表示的是运行 时的参数。参数传递的形式为“Java类名称 参数1 参数2...”

static申明方法  

使用static申明的方法又称为类方法,Person_1.setCountry("B city"); 同时修改多个对象的属性

非static声明的方法可以去调用static声明的属性或方法

但是static声明的方法是不能调用非static类型声明的属性或者方法的

class Person_1{
	private String name;
	private int age;
	public static  String country = "A city";
	
	public static void setCountry(String c){
		country = c;
	}
	
	public static String getCountry(){
		return country;
	}
	
	public Person_1(String n,int a){
		this.name = n;
		this.age = a;
	}
	
	public void info(){
		System.out.println("name:"+this.name+"	"+"age:"+this.age+"	"+"city:"+this.country);
	}
};


public class static_test {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Person_1 p1 = new Person_1("zhangsan",30);
		Person_1 p2 = new Person_1("wangwu",40);
		p1.info();
		p2.info();
		//p1.country = "B city";
		Person_1.setCountry("B city");
		p1.info();
		p2.info();
	}

}

可以通过static还统计实例化了多少个对象

class demo{
	private static int count = 0;
	public demo(){
		count++;
		System.out.println("No."+count);
	}
}


public class static_count {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		new demo();
		new demo();
		new demo();
	}

}

 给主方法的args传递参数,然后统计传递的参数的个数

public class HelloWprdApp {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int num = 0,sum = 0;
		char num1 = 97;

		if(args.length != 3){
			System.out.println("<3");
			System.exit(1);
		}
		
		for(int i=0;i<args.length;i++){
			System.out.println("name:"+args[i]);
		}
	}
}
原文地址:https://www.cnblogs.com/tonglin0325/p/5192329.html