创建一个对象实体类:
package test; public class StudentClass { //此类StudentClass的属性 private int stu_id; private String stu_name; //无参构造方法 public StudentClass() { super(); } //有参构造方法 public StudentClass(int stu_id, String stu_name) { super(); this.stu_id = stu_id; this.stu_name = stu_name; } //属性的setter和getter方法,用来给对象StudentClass赋值 public int getStu_id() { return stu_id; } public void setStu_id(int stu_id) { this.stu_id = stu_id; } public String getStu_name() { return stu_name; } public void setStu_name(String stu_name) { this.stu_name = stu_name; } @Override //override :子类(StudentClass) 重写父类(Object)的方法, public String toString() { return "StudentClass [stu_id=" + stu_id + ", stu_name=" + stu_name + "]"; } }
下一步建立一个main方法测试:
package test; /** * 学生类-测试 * @author Drew * */ public class TestStudentClass { public static void main(String[] args) { //创建一个实体对象 StudentClass studentClass = new StudentClass(21, "SuperDrew"); //调用学生类的方法toString() System.out.println(studentClass.toString()); } }
测试结果: