[英]Call back interfaces in Java
So I'm pretty new to Java and I'm having trouble wrapping my head around this concept. 因此,我对Java还是很陌生,在解决这个概念时遇到了麻烦。
I got it working by doing this: 我这样做可以使其工作:
What I don't understand is that in my WorkerClass I have a constructor that takes as a parameter a type of CallBackInterface. 我不明白的是,在WorkerClass中,我有一个构造函数,该构造函数将CallBackInterface类型作为参数。
In my Main Activity class I make a instance of my WorkerClass, by passing the current instance of Main Activity..why does it work? 在我的Main Activity类中,通过传递Main Activity的当前实例来创建WorkerClass的实例。为什么它起作用? Shouldn't it give me an error because the constructor from WorkerClass requires a different parameter?
它不应该给我一个错误,因为WorkerClass的构造函数需要一个不同的参数吗?
Sorry if this sounds dumb, but I wanna understand why it works, and not just remember that it works like this so I will just use it in the future. 抱歉,这听起来很愚蠢,但我想了解为什么会这样,而不是只记得它像这样工作,所以将来我会用它。
Your activity implements CallBackInterface, so you are not passing a main activity instance into the constructor, but rather instance of CallbackInterface implementation. 您的活动实现了CallBackInterface,因此您没有将主要活动实例传递给构造函数,而是传递了CallbackInterface实现的实例。
If you remove this implementation you will get an error. 如果删除此实现,则会收到错误消息。
why does it work?
为什么行得通?
it works because instead of thinking: 它之所以有效,是因为它没有思考:
WorkerClass needs an interface in the constructor WorkerClass 在构造函数中需要一个接口
you can(must) think as 您可以(必须)认为是
WorkerClass needs "something" that can do a callback in the constructor . WorkerClass需要可以在构造函数中执行回调的 “操作” 。
MainActivity implements that CallbackInterface so this (the actually instance of the main Activity) is holding that contract and can be pass as argument in the constructor. MainActivity实现了该CallbackInterface,因此它 (主Activity的实际实例)持有该合同,并且可以在构造函数中作为参数传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.