static
创建Javabean类
public class student {private int age;private String name;private String gender;public student() {}public student(int age, String name, String gender) {this.age = age;this.name = name;this.gender = gender;}/*** 获取* @return age*/public int getAge() {return age;}/*** 设置* @param age*/public void setAge(int age) {this.age = age;}/*** 获取* @return name*/public String getName() {return name;}/*** 设置* @param name*/public void setName(String name) {this.name = name;}/*** 获取* @return gender*/public String getGender() {return gender;}/*** 设置* @param gender*/public void setGender(String gender) {this.gender = gender;}public void show(){System.out.println(name+","+age+","+gender);}public void study(){System.out.println(name+"正在学习。");}
}
运行
public class test {public static void main(String[] args) {student s1=new student();s1.setName("张三");s1.setAge(23);s1.setGender("男");s1.study();s1.show();student s2=new student();s2.setName("李四");s2.setAge(24);s2.setGender("女");s2.study();s2.show();}
}
加入老师名字
public class student {private int age;private String name;private String gender;public static String teachername;public student() {}public student(int age, String name, String gender) {this.age = age;this.name = name;this.gender = gender;}public student(int age, String name, String gender, String teachername) {this.age = age;this.name = name;this.gender = gender;this.teachername = teachername;}/*** 获取* @return age*/public int getAge() {return age;}/*** 设置* @param age*/public void setAge(int age) {this.age = age;}/*** 获取* @return name*/public String getName() {return name;}/*** 设置* @param name*/public void setName(String name) {this.name = name;}/*** 获取* @return gender*/public String getGender() {return gender;}/*** 设置* @param gender*/public void setGender(String gender) {this.gender = gender;}public void show(){System.out.println(name+","+age+","+gender+","+teachername);}public void study(){System.out.println(name+"正在学习。");}}
每次赋值老师名字太麻烦,在定义类中老师多加入static
即为public static String teachername;类中所有对象共享同一个老师
用student.teachername=''李白'';即可
static表示静态,是Java中的一个修饰符,可以修饰成员方法,成员变量,分别叫静态变量、静态方法。
静态变量:被该类所有对象共享、不属于对象,属于类,随类的加载而加载,优先对象存在
调用方式分为类名调用(student.teachername=''李白'';)、对象名调用(s1.teachername=''李白'';)。
静态方法:多用在测试类和工具类中,Javabean很少会用
调用方式:类名调用、对象名调用
工具类:帮助我们做一些事情的,但是不描述任何事物的类
类名见名知意,私有化构造方法,方法定义为静态
例如:
测试类:用来检查其他类是否书写正确,带main方法的类,是程序的入口
static的注意事项:
1、静态方法只能访问静态变量和静态方法
2、非静态方法可以访问静态变量或者静态方法,也可以访问非静态的成员变量和成员方法。
3、静态方法中没有this关键字