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

标签 java upcasting

我正在 Bruce Eckel 的《Thinking in Java 第四版》中进行以下练习:

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 是一种 Amphibian,因此 Frog 可以做 Amphibian 能做的任何事情。 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/

相关文章:

c++ - 我可以使用 C 风格的转换将派生类转换为私有(private)基类吗?

c++ - 组件系统的逆向转换

java - Java 6 中的向下转型有多昂贵?

c++ - 向上转型指针引用

java - 使用列表创建队列时出现编译错误

c++ - 没有函数指针参数的隐式向上转换?

java - JVM 允许用结构体创建语言吗?

Java Netbeans 堆大小

java - 为什么我的服务启动了两次?

java - 使用 springs RESTtemplate 检索 Jsonobjects 列表时出现异常