Search code examples
javaobjectpolymorphism

Java object oriented programming and polymorphism


Suppose there are 20 subclasses derived from the main class. Suppose each class also has its own properties. Let's say we have a manager class; it takes the main class as a parameter and adds a database. We can give the parameter as polymorphic, yes, but when adding a database, its own, special features cannot be accessed with polymorphism. Since there are 20 pieces, it does not make much sense to use instance of separately in if. What can be done?

public class Person {

    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class Student extends Person {

    private int studentNo;

    public int getStudentNo() {
        return studentNo;
    }

    public void setStudentNo(int studentNo) {
        this.studentNo = studentNo;
    }
}
public class PersonManager {

    public void add(Person person) {
        System.out.println("saved: " + person.getName());
        System.out.println("saved: " + person.getId());
    }
}

Solution

  • You can have a Person.add_database method, and override it on each subclass. Now you keep the fields encapsulated, at the cost of a little bit of boilerplate when creating subclasses.

    public class Person {
    
        private int id;
        private String name;
    
        ...
    
        public void addDatabase(Datatabase db) {
            // Process the Person-specific fields.
            System.out.println("saved: " + this.getName());
            System.out.println("saved: " + thisgetId());
        }
    }
    
    public class Student extends Person {
    
        private int studentNo;
    
        ...
    
        @Override
        public void addDatabase(Database db) {
            // Handle the Person fields.
            super.addDatabase(db);
            // Handle the fields unique to Student.
            System.out.println("saved: " + this.getStudentNo());
        }
    }
    
    public class PersonManager {
    
        public void add(Person person, Database db) {
            // We don't care about the type of Person, they'll handle themselves.
            person.addDatabase(db);
            // Prints id, name, *and* studentNo if given a student.
        }
    }
    

    Alternatively you can use @annotations to mark the fields to be processed, or reflection to inspect all fields.

    However, those solutions are more "magic". I personally find they create hard-to-debug issues, but some communities are big fans.