AP CS 实践 - OOP
我在 AP CS,正在尝试弄清楚这是否有效。
public interface Controller
public class Widget implements Controller
public class Thingy extends Widget
Controller myControl = new Thingy();
假设顶部的接口/类实际上已定义。第四行(Controller myControl = new Thingy();
)是否有效,或者您不能从这样的接口创建对象?
I am in AP CS and am trying to figure out if this works.
public interface Controller
public class Widget implements Controller
public class Thingy extends Widget
Controller myControl = new Thingy();
Assume that the interfaces/classes at the top are actually defined. Does the forth line (Controller myControl = new Thingy();
) work, or can you not create an object from an interface like that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以。
在本例中,您正在实例化
Thingy
的实例,它是一个具体类。您刚刚将其声明为Controller
类型。这仅仅意味着使用它的任何东西都只能访问接口Controller
中可用的方法(除非它们向下转换,使用反射等)。这是一个很好的做法,因为它允许您交换myControl
的实际实现,并且对象的用户不会关心。You can.
In this case, you are instantiating an instance of
Thingy
, which is a concrete class. You have just declared it as typeController
. That just means anything using it can only access methods available in the interfaceController
(unless they downcast, use reflection, etc). This is good practice because it allows you swap out the actual implementation ofmyControl
and users of the object would not care.它是多态性和继承的基础知识——要完全理解 OOP,您应该熟悉这两个术语。
考虑一下:
您有一个 Car 接口、一个实现 Car 的 SportsCar 对象和一个扩展 SportsCar 的 Porsche 对象。
SportsCar IS-A Car 所以你可以说:
Car myCar = new SportsCar();
Porsche IS-A SportsCar 所以你可以说:
SportsCar myCar = new Porsche();
同样,Porsche IS-A Car 所以你可以肯定地说:
底线是:一个超类(接口,抽象类或其他)可以保存对其子类的引用。
It is basics of polymorphism and inheritance - two terms that you should live and breath to fully understand OOP.
Consider this:
You have a Car interface, a SportsCar object which implements Car and a Porsche object which extends SportsCar.
SportsCar IS-A Car so you could say:
Car myCar = new SportsCar();
Porsche IS-A SportsCar so you could say:
SportsCar myCar = new Porsche();
By the same token, Porsche IS-A Car so you can definitely say:
Bottom line is: A superclass (interface, abstract class or whatever) can hold references to its subclasses.
这将创建类 Thingy 的实例,它实现 Controller。 Controller接口本身无法实例化。
This creates an instance of the class Thingy, which implements Controller. The Controller interface itself cannot be instantiated.