简体   繁体   English

如何在Java方法中将接口的实现作为变量传递?

[英]How to pass an implementation of an interface as a variable in a method in Java?

We have an interface Math . 我们有一个Math接口。

We have two implementations of Math (say they are called Math1 and Math2 ). 我们有两个Math实现(例如,它们分别称为Math1Math2 )。 A small part of the project is being able to switch between the two. 该项目的一小部分能够在两者之间进行切换。

In a class (say its called ClassName ) we were provided by our instructor, we have: 在一个类(说其所谓的ClassName ),我们被我们的教师提供,我们有:

public static int evaluate(Math impl)

I have: 我有:

ClassName.evaluate(Math1);

It says it cannot find symbol. 它说找不到符号。 I tried putting it in quotes, but then that's a string. 我尝试将其用引号引起来,但这是一个字符串。 I've tried to google things to try, but I'm not finding anything that helps (maybe I'm just searching for the wrong thing). 我已经尝试过尝试使用Google进行搜索,但是找不到任何有帮助的东西(也许我只是在搜索错误的东西)。 The files are in the same package. 这些文件位于同一软件包中。

How do I pass the interface implementation? 如何通过接口实现?

You are passing the class name instead of a class instance. 您正在传递类名而不是类实例。

Try this: 尝试这个:

// Evaluate with Math1.
Math m1 = new Math1();
ClassName.evaluate(m1);

// Evaluate with Math2.
Math m2 = new Math2();
ClassName.evaluate(m2);

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

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