javadot-operator

How does it work when I have two methods inside .set() method?


I am new to java, and I need help understanding what the code is trying to do. I am interested on the last line( sd.setId(sh.getGrade().getSchoolId());). I know it is setting using setId in sd object, but then I am bit confused what the rest of the line(sh.getGrade().getSchoolId()) is trying to do. Does getSchoolId() method called first and then sh.getGrade() and set everything in sd? How do I read a code when there are multiple dot(.) operators in a single line of code?

while (oneIter.hasNext()) {
 ShoolHistory sh= (ShoolHistory) oneIter.next();
 ScoolDetailId sd = new ScoolDetailId();
 sd.setId(sh.getGrade().getSchoolId());

Solution

  • For something like this it would be easiest to just split each command open into several lines. Then your result will be:

    while (oneIter.hasNext()) {
        ShoolHistory sh = (ShoolHistory) oneIter.next();
        ScoolDetailId sd = new ScoolDetailId();
        Grade grade = sh.getGrade(); // I'm just assuming some types here and for the id
        Integer id = grade.getSchoolId(); // I like btw the usage of all possible variations of writing "school"
        sd.setId(id);
    }
    

    So, if you have a line with multiple dot-operators, you start just reading left to right as you would normally do. Then, if it is like here used as arguments for some methods, you go from inside to outside.