gpt4 book ai didi

java - 在 Java 中向上转换子类引用

转载 作者:行者123 更新时间:2023-11-30 06:14:05 28 4
gpt4 key购买 nike

我正在 Bruce Eckel 的 Thinking in Java 4th Edition 中做以下练习:

Exercise 16: (2) Create a class called Amphibian. From this, inherit a class called Frog. Put appropriate methods in the base class. In main(), create a Frog and upcast it to Amphibian and demonstrate that all the methods still work.

Frog f = new Frog();Amphibian f = new Frog(); 有什么区别:

class Amphibian {
void go() { System.out.println("go"); }
void stop() { System.out.println("stop!"); }
}

class Frog extends Amphibian {
void go() { System.out.println("not go"); }
}

public class EFrog {
public static void main(String[] args) {
Frog f = new Frog();
f.go();
}
}

最佳答案

But I don't understand What is the difference between Frog f = new Frog(); and Amphibian f = new Frog();

为了理解差异,让我们在 Frog 中添加另一个 Amphibian 中没有的方法

class Frog extends Amphibian {
void go() { System.out.println("not go"); }
void come() { System.out.println("come"); }
}

现在让我们看看有什么区别:

public class EFrog {
public static void main(String[] args) {
Frog f = new Frog();
f.go();
f.come();
Amphibian a = f;
a.come();//this won't compile
}
}

底线。 Frog 是一种两栖动物,所以Frog 可以做任何两栖动物 能做的事。 Amphibian 不是 Frog 所以 Amphibian 不能做 Frog 能做的所有事情。

当你说 Amphibian a = new Frog() 时,你是在为一个接口(interface)编程(不是 java 接口(interface),而是接口(interface)的一般含义)。当您说 Frog f = new Frog() 时,您正在为实现编程。

现在来看本书要求您尝试的实际问题:

In main( ), create a Frog and upcast it to Amphibian and demonstrate that all the methods still work.

public class EFrog {
public static void main(String[] args) {
Frog f = new Frog();
Amphibian g = (Amphibian)f;//this is an upcast
g.go(); //okay since Amphibian can go
g.come();//not okay since Amphibian can't come
}
}

我不认为你想问向上转换有什么用,但既然标题已经被其他人编辑过,为什么不也回答这个问题呢?向上转型在某些情况下很有用,例如显式调用重载方法的特殊形式。参见 this回答更多详细信息。

关于java - 在 Java 中向上转换子类引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30914253/

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