How to call a method in another class in Java?

I currently have two classes. class class and school class. I would like to write a method in the School class to call public void setTeacherName (String newTeacherName) from the class 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
}  
+3
source share
5 answers

You must use the names of your classes. After that, do it in your school class,

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

I would also recommend using some IDE, such as eclipse, which can help you with your code, for example, generating getters and setters for you. Example: right-click Source → Generate Recipients and Setters

+10
source

Try the following:

public void addTeacherToClassRoom(classroom myClassRoom, String TeacherName)
{
    myClassRoom.setTeacherName(TeacherName);
}
+6
source
class A{
  public void methodA(){
    new B().methodB();
    //or
    B.methodB1();
  }
}

class B{
  //instance method
  public void methodB(){
  }
  //static method
  public static  void methodB1(){
  }
}
+3
source

at school,

public void addTeacherName(classroom classroom, String teacherName) {
    classroom.setTeacherName(teacherName);
}

BTW , use the Pascal Case for class names. In addition, I would suggest Map<String, classroom>matching the class name in the class.

Then, if you use my suggestion, this will work

public void addTeacherName(String className, String teacherName) {
    classrooms.get(className).setTeacherName(teacherName);
}
+2
source

Instead of using this in your current class setClassRoomName("aClassName");you need to useclassroom.setClassRoomName("aClassName");

You must add a class' and at a point like

yourClassNameWhereTheMethodIs.theMethodsName();

I know this is a very late answer, but if someone starts to learn Java and accidentally sees this post, he knows what to do.

-1
source

Source: https://habr.com/ru/post/1783388/


All Articles