Issue
I am trying to add the Lists "studentList" and "handerwerkerList" to the new ArrayList plist. So i want my Objects to be all in one List. The other Lists have more parameters than the person objects. But i want to convert the other lists so they fit in the new list.
static List <Person> personList = new ArrayList <Person>();
static List <Student> studentList = new ArrayList <Student>();
static List <Handwerker> handwerkerList = new ArrayList <Handwerker>();
public static void main (String[] args) {
PrintWriter out = new PrintWriter(System.out);
testDifferentTypes(out);
testRechnungen(out);
out.flush();
}
public static void testDifferentTypes(PrintWriter out) {
personList.add(new Person("Anton", "Kripp", 2001));
studentList.add(new Student("Sarah", "Hirschfelder", 1993, "Wirschaftinformatik", 123456));
studentList.add(new Student("Patrick", "Huf", 1990, "Informatik", 654321));
studentList.add(new Student("AJ", "Kurpieweit", 1995, "Psychologie", 250702));
handwerkerList.add(new Handwerker("Niko", "Budic", 2005, "Rohrleger", 9.82));
ArrayList<Person> plist = new ArrayList <Person>();
for(Person person : personList) {
plist.add(person);
}
for(Person person : studentList) {
plist.add(person);
}
for (Person person : handwerkerList) {
plist.add(person);
}
}
public class Student extends Person{
protected String studienfach;
protected int matrikelNr;
public Student(String Vorname, String Nachname, int geburtsjahr, String studienfach, int matrikelNr) {
super(Vorname, Nachname, geburtsjahr);
this.studienfach = studienfach;
this.matrikelNr = matrikelNr;
}
public Student(Person person, String studienfach, int matrikelNr) {
this(person.Vorname, person.Nachname, person.geburtsjahr,studienfach, matrikelNr);
}
public class Handwerker extends Person{
protected String gewerk;
protected Double stundenlohn;
public Handwerker(String Vorname, String Nachname, int geburtsjahr, String gewerk, Double stundenlohn) {
super(Vorname, Nachname, geburtsjahr);
this.gewerk = gewerk;
this.stundenlohn = stundenlohn;
}
public Handwerker(Person person, String gewerk, Double stundenlohn) {
this(person.Vorname, person.Nachname, person.geburtsjahr, gewerk, stundenlohn);
}
Solution
I recommend you spend some time reading about how inheritance works.
The answer to your question, if Student and Handweker already extend Person, then you can add them to any ArrayList<Person>
directly.
Answered By - Yara
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.