简体   繁体   English

我尝试使用多态性,但我的代码不能像我预期的那样工作,有人可以帮我解决这个问题吗?

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

UserManager.java:用户管理器.java:

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

StudentManager.java: StudentManager.java:

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

Main.java:主要.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.期待 Output:12345 学生添加。

Real output:12345 user added.添加了真正的 output:12345 用户。

Why i get this output?为什么我得到这个 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.如果您想按预期使用多态,则应将UserManager object 实例化为StudentManager ,因此 JVM 将调用覆盖的add方法。 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);
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我无法在程序中使用PrinterWriter,有人可以帮我解决吗? - I can't use PrinterWriter in my program, could anyone help me figure it out? 如何在这里使用多态来改进代码? - How could I use polymorphism here to improve my code? 为什么多态性不能像我期望的那样起作用? - Why polymorphism does not work as I'd expect in my code? 我的代码遇到了运行时错误,有人可以帮我找出我哪里错了 - i got Runtime Error for my code ,can anyone help me to find out where i am wrong 当我进入该程序时,对#2和#3的选择将不起作用。 谁能帮助我了解为什么它会以这种方式运行? - When I enter this program, my choices for #2 and #3 will not work. Can anyone help me understand why it is behaving this way? 在意图android中出现错误有人尝试解决此错误并帮助我,查看SS,我尝试了三种方法来解决但没有用 - Getting error in intent android somebody try to solve this error and help me,Check out SS,I tried three methods to solve but no use 我的表格程序有问题。 可以告诉我如何解决吗? - I have a problem with my table program. Could one tell me how to solve it? 任何人都可以帮助我解释为什么我的Java方法不能完全按照我的期望去做吗? - Could anyone help me with why my Java method isn't quite doing what I'm expecting it to do? 为什么 Swing 框架有时没有在下面打开我附加了我的代码,任何人都可以帮助我为什么会这样? - Why Swing frame isn't opening sometimes below I attached my code and anyone help me why is it happening? 我尝试在我的小型 android 项目中使用意向电子邮件,但它不起作用。 谁能帮我找出错误? - I tried to use intent email in my small android project but its not working. Can anyone help me to find the error?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM