对于方案三的疑问
方案三中,老师用this.get().get()的方式调用了私有成员变量studentSubject,我没有用this.get().get()方式,而是直接用studentSubject.get()方式也可以成功调用,两者有什么区别吗?
package com.luyue.SchoolProj;
public class Student {
private String stuName;
private String stuNo;
private String stuSex;
private int stuAge;
private Subject sub;
public Student() {
}
public Student(String stuName,String stuNo,String stuSex,int stuAge,Subject sub) {
this.setStuAge(stuAge);
this.setStuName(stuName);
this.setStuNo(stuNo);
this.setStuSex(stuSex);
this.setSubject(sub);
}
public void setSubject(Subject sub) {
this.sub=sub;
}
public Subject getSubject() {
return sub;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
public String getStuSex() {
return stuSex;
}
public void setStuSex(String stuSex) {
if(stuSex!="男"||stuSex!="女")
this.stuSex="男";
else
this.stuSex = stuSex;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
if(stuAge<10||stuAge>=100)
this.stuAge=18;
else
this.stuAge = stuAge;
}
public String info(Subject sub) {
String str="学生信息:\n姓名:"+this.getStuName()+"\n学号:"+this.getStuNo()+"\n性别:"+this.getStuSex()+"\n年龄:"+this.getStuAge()+"\n专业编号:"+sub.getSubNo()+"\n专业年限:"+sub.getSubLife();
return str;
}
public String info() {
String str="学生信息:\n姓名:"+this.getStuName()+"\n学号:"+this.getStuNo()+"\n性别:"+this.getStuSex()+"\n年龄:"+this.getStuAge()+"\n专业编号:"+sub.getSubNo()+"\n专业年限:"+sub.getSubLife();
return str;
}
}
package com.luyue.test;
import com.luyue.SchoolProj.Subject;
import com.luyue.SchoolProj.Student;
public class SubTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Subject sub1=new Subject("计算机科学与应用","J0001",4);
System.out.println(sub1.info());
System.out.println("======================");
Student stu1=new Student("小明","0015","",200,sub1);
System.out.println(stu1.info());
}
}
正在回答
你好,你说的是通过sub.getSubNo()也可以获得相关信息吗?增加一个Subject参数,对象实例化时直接将subject赋值进去,然后再获取这个属性的相关值,这种思路和第三种方案是一样的,只不过是直接通过属性获取到相关的值,而没有通过getter方法。
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星