gpt4 book ai didi

Java 多态性/转换/方法

转载 作者:搜寻专家 更新时间:2023-11-01 03:21:32 30 4
gpt4 key购买 nike

关于此主题的说明。因此,出于示例目的,假设我有:

public interface Gaming {
void play;
}

public abstract class Console implements Gaming {
void play() {}
}

public class Xbox extends Console {
void play() {}
}

public class XboxOne extends Xbox {
void play() {}
}
  1. 我永远无法直接实例化 Console,因为它是抽象的
  2. 但是我可以将控制台实例化为 xbox

    Console fav = new Xbox();

  3. 如果所有类都定义了play() 方法。如果我调用 fav.play();,它会查看 Xbox 的播放方法,如果它没有播放方法,它会在层次结构中继续向上直到找到该方法?

  4. 此外,如果我执行 ((XboxOne)fav).play(),它会执行 XboxOne 的播放方法吗?还有,如果对象较低,我只能转换它是真的吗在层次结构中?

  5. 如果 Xbox 类有一个 getGamerscore 方法但控制台没有,我会能够运行fav.getGamerScore()吗?

一般问题:

= 左边的类型显示调用方法时 java 将查找的类(最具体的)? (如果它在那里找不到它,它会继续向上层次结构直到找到该方法?)

右边的类型只是代表编译类型。编译java时会查看方法或数据是否属于编译类型,如果是则一切都好? Java 在运行时将不再查看它的编译类型。

转换只是帮助解决编译问题?例如,如果我想使用某种方法,但我的对象编译类型类似于接口(interface)或抽象类之类的东西,那么我进行强制转换,以便在我尝试访问运行时类型的方法时编译器不会提示?

如果我说错了什么请纠正我我只是想把所有的规则都记在脑子里。另外,如果有人有任何有用的资源,那将是很棒的。

**我意识到我没有使用游戏界面

最佳答案

你需要区分两件事

  1. 静态类型

这是在编译时已知的以及将用于方法签名查找的内容。因此,如果您有 Console fav = new Xbox(),则 fav 的静态类型将为 Console。因此,如果您尝试调用 fav.play(),编译器将在 Console 类中寻找 play 签名;如果 Console 不支持这个方法,那么 Java 甚至不会编译它。

  1. 动态类型

这是运行时的变量,所以在启动程序 Console fav = new Xbox() 后,fav 的动态类型将是 Xbox(但静态类型仍然是 Console)。

现在回答你的问题

If all of the classes have a defined play method. If I call fav.play(); it will look at the Xbox's play method, if it did not have a play method it would continue up the hierarchy until it found that method?

如果对于所有类,您还指基 Console 类(至少是抽象方法),那么是的。

Also if I did ((XboxOne)fav).play() it would do the XboxOne's play method?, also is it true that I can only cast an object if it's lower in the hierarchy?

您始终可以向上转换 - 从更具体的 (Xbox) 到更通用的 (Console);向下转型只在某种程度上是可能的——如果它有机会成功的话。所以通常向下转换为动态类型应该会成功。 (例如 Console fav = new Xbox() + (Xbox)console)

If the Xbox class had a getGamerscore method but the console didn't, would I be able to run fav.getGamerScore()?

没有,如前所述; favConsole,因此不知道您所说的 getGamerScore 是什么意思。但是,您仍然可以执行 ((XBox) fav).getGamerScore

Casting just helps get past compile problems?

转换可能非常危险,因为您要对变量做出假设。如果您正在调用 ((XBox) fav).getGamerScore,那么您已经知道类型必须是 Xbox 并且具有 Console fav 可能是错误,因为您不能在其中分配任何类型的控制台。

关于Java 多态性/转换/方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29435258/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com