日期:2014-05-20  浏览次数:20827 次

求教关于访问封装类的问题
如果在一个封装的类中,对field设置private,那么在主方法或其他方法中如何访问field,如果要在类中设置setter和getter方法进行调用的话,该如何设置,如果需要使用setter和getter方法,那么是否还需要自定义构造器,本人JAVA刚开始学到面向对象,刚做了个课后习题,说要把类都封装好,感觉有点蒙,多谢赐教了!

------解决方案--------------------
我大致给你封装了一下
package com.fzw.csdn.test;

public class Person {
private int age;
private String name;
private String sex;

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

}



package com.fzw.csdn.test;

public class Student {

private String stuClass;// 班级
private String stuType;// 文理生
private String stuSpe;// 专业
private Person person;

public String getStuClass() {
return stuClass;
}

public void setStuClass(String stuClass) {
this.stuClass = stuClass;
}

public String getStuType() {
return stuType;
}

public void setStuType(String stuType) {
this.stuType = stuType;
}

public String getStuSpe() {
return stuSpe;
}

public void setStuSpe(String stuSpe) {
this.stuSpe = stuSpe;
}

public Person getPerson() {
return person;
}

public void setPerson(Person person) {
this.person = person;
}


}



package com.fzw.csdn.test;

public class Teacher {
private String teaClass;// 代课班级
private String teaCourse;// 所带课程
private String teaRole;// 代课版中角色
private Person person;

public String getTeaClass() {
return teaClass;
}

public void setTeaClass(String teaClass) {
this.teaClass = teaClass;
}

public String getTeaCourse() {
return teaCourse;
}

public void setTeaCourse(String teaCourse) {
this.teaCourse = teaCourse;
}

public String getTeaRole() {
return teaRole;
}

public void setTeaRole(String teaRole) {
this.teaRole = teaRole;
}

public Person getPerson() {
return person;
}

public void setPerson(Person person) {
this.person = person;
}

}


package com.fzw.csdn.test;

public class School {
private Student student;
private Teacher teacher;

public Student getStudent() {
return student;
}

public void setStudent(Student student) {
this.student = student;
}

public Teacher getTeacher() {
return teacher;
}

public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}


还可以继续封装,剩下的自己解决