Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method in another class in Java?

Tags:

java

Currently I have two classes. a classroom class and a School class. I would like to write a method in the School class to call public void setTeacherName(String newTeacherName) from the classroom class.

classroom.java

public class classroom {
    private String classRoomName;
    private String teacherName;

    public void setClassRoomName(String newClassRoomName) {
        classRoomName = newClassRoomName;

    }

    public String returnClassRoomName() {
        return classRoomName;
    }

    public void setTeacherName(String newTeacherName) {
        teacherName = newTeacherName;

    }

    public String returnTeacherName() {
        return teacherName;
    }
}

School.java

import java.util.ArrayList;

public class School {
    private ArrayList<classroom> classrooms;
    private String classRoomName;
    private String teacherName;

    public School() {
        classrooms = new ArrayList<classroom>();
    }

    public void addClassRoom(classroom newClassRoom, String theClassRoomName) {
        classrooms.add(newClassRoom);
        classRoomName = theClassRoomName;
    }

    // how to write a method to add a teacher to the classroom by using the
    // classroom parameter
    // and the teachers name
}  
like image 484
Puchatek Avatar asked Jan 04 '11 11:01

Puchatek


Video Answer


2 Answers

You should capitalize names of your classes. After doing that do this in your school class,

Classroom cls = new Classroom();
cls.setTeacherName(newTeacherName);

Also I'd recommend you use some kind of IDE such as eclipse, which can help you with your code for instance generate getters and setters for you. Ex: right click Source -> Generate getters and setters

like image 117
ant Avatar answered Sep 20 '22 10:09

ant


Try this :

public void addTeacherToClassRoom(classroom myClassRoom, String TeacherName)
{
    myClassRoom.setTeacherName(TeacherName);
}
like image 39
LaGrandMere Avatar answered Sep 19 '22 10:09

LaGrandMere