AP CS 实践 - OOP

发布于 2025-01-04 13:37:08 字数 298 浏览 1 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

她比我温柔 2025-01-11 13:37:08

你可以。

在本例中,您正在实例化 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 type Controller. That just means anything using it can only access methods available in the interface Controller (unless they downcast, use reflection, etc). This is good practice because it allows you swap out the actual implementation of myControl and users of the object would not care.

吃→可爱长大的 2025-01-11 13:37:08

它是多态性和继承的基础知识——要完全理解 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 所以你可以肯定地说:

Car myCar = new Porsche();

底线是:一个超类(接口,抽象类或其他)可以保存对其子类的引用。

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:

Car myCar = new Porsche();

Bottom line is: A superclass (interface, abstract class or whatever) can hold references to its subclasses.

金兰素衣 2025-01-11 13:37:08

这将创建类 Thingy 的实例,它实现 ControllerController接口本身无法实例化。

This creates an instance of the class Thingy, which implements Controller. The Controller interface itself cannot be instantiated.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文