简体   繁体   中英

I try to use polymorphism but my code does not work as i excpected, could anyone help me solve this problem?

UserManager.java:

public class UserManager {
        public void add(User user) {
            System.out.println(user.getUserNumber() + " user added");
        }
}

StudentManager.java:

public class StudentManager extends UserManager {
    @Override
    public void add(User user) {
        System.out.println(user.getUserNumber() + "  student added");
    }
}

Main.java:

public class Main {
    public static void main(String[] args) {
        Student student1 = new Student();
        student1.setUserNumber("12345");

        UserManager userManager = new UserManager();       
        userManager.add(student1);

    }
}
    

Expecting Output:12345 student added.

Real output:12345 user added.

Why i get this output?

If you want to use polyformphism as you expected, you should instantiate the UserManager object as StudentManager , so the JVM will invoke the overriden add method. Here is the right way to do that:

public class Main {
   public static void main(String[] args) {
       Student student1 = new Student();
       student1.setUserNumber("12345");

       UserManager userManager = new StudentManager();       
       userManager.add(student1);
   }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM