I am implementing a factory pattern to create two concrete classes in an abstract which has the factory methods overloaded (see below):
public abstract class User {
...
public static User make(int id, String name) {
return new Admin(id, name);
}
public static User make(int id, int student_id, String name) {
return new Student(id, student_id, name);
}
}
Here is the factory calls:
ArrayList<User> users = new ArrayList<>(
Arrays.asList(
User.make(1000, "Andy"), // makes new Admin
User.make(1001, 101001, "Bob") // makes new Student
)
);
Here is the Admin class:
public class Admin extends User {
...
// constructor
protected Admin(int id, String name) {
super(id, name);
}
...
}
Here is the Student class:
public class Student extends User {
...
// constructor
protected Student(int id, int student_id, String name) {
super(id, name);
this.student_id = student_id;
}
...
}
Each of these concretes are placed into a User ArrayList. I have a function (below) which loops through the list and does runtime inference to call particular methods unique to each concrete; however I am getting a ClassCastException error in my IDE stating Admin cannot be cast to Student.
Full exception message is: Exception in thread "main" java.lang.ClassCastException: presentation_layer.Admin cannot be cast to presentation_layer.Student
public class App {
...
public static void main(String[] args) {
ArrayList<User> users = new ArrayList<>(
Arrays.asList(
User.make(1000, "Andy"), // makes new Admin
User.make(1001, 101001, "Bob") // makes new Student
)
);
users.forEach((u) -> {
if (u instanceof Admin)) {
System.out.println("hello admin");
((Admin)u).anAdminFunc();
} else if (u instanceof Student)) {
System.out.println("hello student");
((Student)u).aStudentFunc();
}
});
}
...
}
When I comment out the concrete method calls, the respective print statements output as expected with no errors; however, when trying to use these unique method calls between each loop iteration I get the casting error. Can you please advise how this can be addressed and what I am doing wrong, with either my approach at inference or my approach at a factory pattern?
use instanceof instead. also, you might want to rethink your use of inheritance if you find yourself doing lots of casting
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With