I am trying to figure out how, if possible, to copy one object into another. It is not as simple as I mean because I am trying to copy objects from class B into an object from class A.
I will try to show examples of code.
public class A {
ArrayList<String> areaList = new ArrayList<>
}
Then I create that actual area in the next class, or maybe I should be creating it in the first class.
public class B {
A area = new A[10];
}
And here is the next class:
public class C {
B teachers = new B[5];
}
I want to create multiple different areas with multiple different teachers. In area 1 lets say its math, I want 4 different teachers. I am looking for just name, number, and salary of the teachers so 3 attributes. In area 2, lets say its English, I would like to enter 5 English teachers. But I still want to be able to reference my first area which would be area[0] and see the original 4 teachers I inserted in that list after I add the English teachers to area[1]. I wasn't sure how to do that or how to even approach that because when I try to set them equal, it compiles an error because they are from different classes technically. I want to see if I can do this without extending class.
I think you mean something like this, hm? If you add one teacher in two different areas it will be the same teacher because you will add a reference to the list.
public class MainClass {
public static void main(String[] args) {
ArrayList<Area> areasList = new ArrayList<>(10);
Area math = new Area("math");
areasList.add(math);
math.addTeacher(new Teacher("Mr. Freeman", 3500f));
math.addTeacher(new Teacher("Mr. Greedy", 3200f));
}
}
class Area {
private String name;
private List<Teacher> teachersList;
public Area(String name) {
this.name = name;
this.teachersList = new ArrayList<Teacher>(10); //define what type of list do you want
}
public String getName() {
return name;
}
public List<Teacher> getTeachersList() {
return teachersList;
}
public void setName(String name) {
this.name = name;
}
public void addTeacher(Teacher teacher) {
this.teachersList.add(teacher);
}
public void removeTeacher(Teacher teacher) {
this.teachersList.remove(teacher);
}
}
class Teacher {
String name;
float salary;
public Teacher(String name, float salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.