<pre name="code" class="java"><span style="font-size:24px;color:#330099;">class ArrayTool {
//为什么使用到static静态方法,当使用static方法,没有使用到方法中的数据时就用静态方法
private ArrayTool(){} //使用private修饰构造方法,使类中的方法只能使用" 类.方法 "调用
public static int getMax(int[] arr){
int max=0;
for(int x=1;x<arr.length;x++){
if(arr[x]>arr[max]){
max=x;
}
}
return arr[max];
}
public static int getMin(int[] arr){
int min=0;
for(int x=1;x<arr.length;x++){
if(arr[x]>arr[min]){
min=x;
}
}
return arr[min];
}
//冒泡排序,从小到大
public static void selectSort(int[]arr){
for(int x=0;x<arr.length;x++){
for(int y=0;y<x;y++){
if(arr[x]<arr[y]){
swap(arr,x,y);
}
}
}
}
//swap方法
private static void swap(int[] arr,int a,int b)
{
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
public static void printArray(int[] arr){
System.out.print("[");
for(int x=0; x<arr.length; x++){
if(x!=arr.length-1)
System.out.print(arr[x]+", ");
else
System.out.println(arr[x]+"]");
}
}
}
public class ArrayToolDome {
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[]={12,3,45,67,84,6536,856,25,23};
int max=ArrayTool.getMax(arr);
System.out.println("max= "+max);
int min=ArrayTool.getMin(arr);
System.out.println("min= "+min);
ArrayTool.selectSort(arr);
ArrayTool.printArray(arr);
}
</span>
静态代码块
<span style="font-size:24px;color:#330099;">
</span><pre name="code" class="java"><span style="font-size:24px;color:#330099;">/*
静态代码块。
格式:
static
{
静态代码块中的执行语句。
}
特点:随着类的加载而执行,只执行一次,并优先于主函数。
用于给类进行初始化的。
*/
class StaticCode
{
int num=9;
StaticCode(){ //构造方法 随着类的加载而加载
System.out.println("a");
}
static{ //随着类的加载而加载
//System.out.println("static代码块"+this.num); //静态代码块无法访问非静态变量
System.out.println("static代码块");
}
{
System.out.println("构造代码块"+this.num); //构造代码块可以访问非静态变量
}
public static void show(){
System.out.println("show run");
}
}
class StaticDomeCode
{
static{
System.out.println("b");
}
public static void main(String[] args) {
new StaticCode();
new StaticCode(); //static代码块,随着类的加载而执行,只执行一次,并优先于主函数
System.out.println("over");
//StaticCode.show();
//StaticCode s=new StaticCode(); //The value of the local variable s is not used
//但是为什么会出现“ 构造代码块 a ”的结果
//由于创建并实例化了对像,会加载类
StaticCode s=null; //在栈内存中开辟了空间,但没有实例化对象也就无法加载类
s =new StaticCode(); //此时实例化了对象,即在堆内存有了指向
}
static{
System.out.println("c");
}
}</span>
<span style="color:#333399;">执行结果:</span>
b
c
static代码块
构造代码块9
a
构造代码块9
a
over
构造代码块9
a
静态:static用法:是一个修饰符除了可以被对象调用外,还可以直接被类名调用。类名.静态成员。
static特点:
1,随着类的加载而加载。
也就说:静态会随着类的消失而消失。说明它的生命周期最长。
2,优先于的对象存在
明确一点:静态是先存在。对象是后存在的
3,被所有对象所共享
4,可以直接被类名所调用。
实例变量和类变量的区别:
1,存放位置。
类变量随着类的加载而存在于方法区中。
实例变量随着对象的建立而存在于堆内存中。
2,生命周期:
类变量生命周期最长,随着类的消失而消失。
实例变量生命周期随着对象的消失而消失。
静态使用注意事项:
1,静态方法只能访问静态成员。
非静态方法既可以访问静态也可以访问非静态。
2,静态方法中不可以定义this,super关键字。
因为静态优先于对象存在。所以静态方法中不可以出现this。
3,主函数是静态的。
静态的利弊
利处:对对象的共享数据进行单独空间的存储,节省空间。没有必要每一个对象中都存储一份。
可以直接被类名调用。
弊端:生命周期过长。
访问出现局限性。(静态虽好,只能访问静态。)