当前位置: 代码迷 >> 综合 >> java标准类即JAVA Bean
  详细解决方案

java标准类即JAVA Bean

热度:91   发布时间:2024-03-06 03:12:07.0

标准的JAVA类也叫做JAVA Bean类,一个标准类通常需要四个部分组成:
1.所有成员变量都是用private关键字修饰
2.为每一个成员变量都编写一对Getter/Setter方法
3.定义无参构造方法
4.定义全参构造方法
注意:如果你没有定义构造方法,编译器会自动给你一个默认无参构造方法,如果有,则不再给。
这里拿Student学生类举例子:

public class Student {//定义成员变量private  int id;//学号private String name;//姓名private int age;//年龄private boolean male;//性别//定义无参构造方法public PrintArray() {}
//定义全参构造方法public PrintArray(int id, String name, int age, boolean male) {this.id = id;this.name = name;this.age = age;this.male = male;}public int getId() {return id;}public void setId(int id) {this.id = id;}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 boolean isMale() {return male;}public void setMale(boolean b) {this.male = b;}
}

让我们实现一下:

public class Person {public static void main(String[] args) {//首先进行类的实例化//调用无参构造方法Student stu1 = new Student();stu1.setId(2019);stu1.setName("彭于晏");stu1.setAge(28);stu1.setMale(true);System.out.println("学号:"+stu1.getId()+" 姓名:"+stu1.getName()+" 年龄:"+stu1.getAge()+" 是否是男生:"+stu1.isMale());//调用全参构造方法Student stu2 = new Student(2019,"彭于晏",28,true);System.out.println("学号:"+stu2.getId()+" 姓名:"+stu1.getName()+" 年龄:"+stu1.getAge()+" 是否是男生:"+stu1.isMale());}

输出结果为:
学号:2019 姓名:彭于晏 年龄:28 是否是男生:true
学号:2019 姓名:彭于晏 年龄:28 是否是男生:true