简体   繁体   English

包中类的多态性模仿

[英]Polymorphism mimic for class in packages

OOP allows for inheritance for abstract methods, thus every child with own implementation. OOP允许继承抽象方法,因此每个孩子都有自己的实现。 Such ability cascades to coding an application in general, as such, it calls to one same message at different times and receive different output according to the type of child instantiated. 通常,这种能力会级联以对应用程序进行编码,因此,它在不同的时间调用一个相同的消息,并根据实例化的子代的类型接收不同的输出。 This concept is known as Polymorphism. 这个概念称为多态。

Picture it that Polymorphism gives a developer a chance to create an object. 想象一下,多态为开发人员提供了创建对象的机会。 This object can be assigned a reference to one of multiple classes' instances that both contain a method of the same signature but of different implementation. 可以为该对象分配对多个类实例之一的引用,这些实例都包含具有相同签名但实现方式不同的方法。 This assignment is through conditional statements. 该分配是通过条件语句进行的。 Thereafter calling the method using this object, which in turn, happens to perform different operations depending on the appropriate condition. 此后,使用该对象调用方法,而该对象又会根据适当的条件执行不同的操作。

With the same view but now we are dealing with a Java Application that has many packages that both contain a Class of the same name. 以相同的观点,但是现在我们正在处理一个Java应用程序,该应用程序具有许多包含同名类的包。 A scenario all users of the Application go through a Login class then routes to a Main Menu screen (Main class). 场景该应用程序的所有用户都经过一个Login类,然后路由到Main Menu屏幕(Main类)。 There are two different users thus two versions of the Main class, each of which are in two packages (be it: admin and user), in turn, acting as an entry point for the rest of the appropriate package. 有两个不同的用户,因此Main类的两个版本,每个版本位于两个软件包中(分别是:admin和user),它们充当其余适当软件包的入口点。

Is there a Polymorphism mimic to let us declare an object in the Login class, of which during authentication, then assign a reference to either package mapping from the user type? 是否有一个Polymorphism模拟项可以让我们在Login类中声明一个对象,该对象在身份验证过程中,然后根据用户类型分配对任一程序包映射的引用?

Thereafter, calling reference.Main.setVisible(true); 之后,调用reference.Main.setVisible(true); will open the Main class for the type of the current login user. 将打开当前登录用户类型的Main类。

Have both versions of the menu implement an interface/abstract class. 让两个版本的菜单都实现一个接口/抽象类。 Then use the interface polymorphically in the login class. 然后在登录类中多态使用该接口。

For example, make an abstract class called Menu, and have the userMenu and the adminMenu classes extend Menu. 例如,创建一个名为Menu的抽象类,并让userMenu和adminMenu类扩展Menu。 In your Login class, create a field of type Menu (for the sake of example call it m). 在您的Login类中,创建一个Menu类型的字段(为方便起见,将其命名为m)。 Assign either a new UserMenu or AdminMenu at runtime, depending on who the user is. 在运行时分配新的UserMenu或AdminMenu,具体取决于用户是谁。 Then when you want to open the menu, call m.setVisible(true) 然后,当您要打开菜单时,调用m.setVisible(true)

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

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