1.静态变量static
1.1什么是static
1.2什么是静态变量
1.3静态变量代码示例:
java">public class Student {private String name;private int age;private String id;static String teacherName;public Student() {}public Student(String name, int age, String id) {this.name = name;this.age = age;this.id = id;}
比如Student类,有静态变量teacherName
教师是被所有学生共享的,所以teacherName可以作为静态变量
用static修饰,则该变量就可以被所有对象共享,所有对象的teacherName都是同一个值
而且成员变量默认是public
Student.teacherName="阿伟老师";
可以先于对象被创建
java">public class Studenttset {public static void main(String[] args) {Student.teacherName="张老师";Student s1=new Student("小红",21,"heima001");System.out.println(s1.teacherName);}
}
2.静态方法
在本类中,直接方法名就能调用,要调用其他类的方法,则要用类名调用
工具类:
2.1.什么是工具类,有什么作用
2.2.工具类如何构造
2.3工具类相关练习
2.3.1定义数组工具类
工具类代码:
java">package com.itbaima.exe05;public class ArrayUtil {//构造方法一定是私有的,目的是防止创建对象private ArrayUtil(){}public static String printArr(int []arr){StringBuilder sb=new StringBuilder();sb.append("[");for (int i = 0; i < arr.length; i++) {if(i==arr.length-1){sb.append(arr[i]);}else{sb.append(arr[i]).append(",");}}sb.append("]");return sb.toString();}public static double getAverage(double arr[]){double sum=0;for (int i = 0; i < arr.length; i++) {sum=sum+arr[i];}return sum/arr.length;}
}
测试类代码:
java">public class TestDemo {public static void main(String[] args) {int arr[]={1,2,3,4,5};String str=ArrayUtil.printArr(arr);System.out.println(str);double []arr2={5.1,4.6,8.3,4.9,1.3};double result=ArrayUtil.getAverage(arr2);System.out.println(result);}
2.3.2定义学生工具类
JavaBean类代码:
java">package com.itbaima.exe06;public class Student {private String name;private int age;private String gender;public Student() {}public Student(String name, int age, String gender) {this.name = name;this.age = age;this.gender = gender;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}
}
工具类代码:
java">package com.itbaima.exe06;import java.util.ArrayList;public class StudentUtil {private StudentUtil(){}public static int maxstudentAge(ArrayList<Student> list){int max=list.get(0).getAge();for (int i = 0; i < list.size(); i++) {if(list.get(i).getAge()>max){max=list.get(i).getAge();}}return max;}
}
测试类代码:
java">package com.itbaima.exe06;import java.util.ArrayList;public class Test {public static void main(String[] args) {//1.先创建一个集合ArrayList<Student> list=new ArrayList<>();//2.再创建三个学生对象Student s1= new Student("xiaohong",21,"男");Student s2= new Student("xiaolv",22,"女");Student s3= new Student("xiaolan",21,"男");//3.将三个学生加入集合中list.add(s1);list.add(s2);list.add(s3);int age=StudentUtil.maxstudentAge(list);System.out.println(age);}
}