How do you call method in Java from another class to set a teacher's name in a classroom?

You can also directly pass a classroom object to the method.

public void assignTeacherToClassroom(classroom cls, String teacherName) {  
    if (cls != null) {  
        cls.setTeacherName(teacherName);  
        System.out.println("Teacher " + teacherName + " assigned to " + cls.returnClassRoomName());
    } else {  
        System.out.println("Invalid classroom reference!");  
    }  
}

Usage Example:

public static void main(String[] args) {  
    School mySchool = new School();  
    classroom mathClass = new classroom();  
    mathClass.setClassRoomName("Math101");  

    mySchool.addClassRoom(mathClass, "Math101");  

    mySchool.assignTeacherToClassroom(mathClass, "Mrs. Williams");  

    System.out.println("Teacher for Math101: " + mathClass.returnTeacherName());  
}

:heavy_check_mark: Pros:

  • Avoids unnecessary lookups.

  • Clean and straightforward.

:x: Cons:

  • Requires an already-referenced classroom object.