无法理解Java中的继承和重写/重载 [英] Not able to understand the inheritance and overriding/overloading in java

查看:90
本文介绍了无法理解Java中的继承和重写/重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解下面的代码时遇到了问题(对行号进行了注释)

I have problem understanding the below code(commented against the line number)

class Base {
    void m1(Object o) {
    }

    void m2(String o) {
    }
}

public class Overloading extends Base {

    void m1(String s) {
    }

    void m2(Object o) {
    }
public static void main(String[] args) {
    Object o = new Object();
    Base base1 = new Base();
    base1.m1("");//**why this works perfect**
    Base base = new Overloading();
    base.m2(o);// **why compile time error** - The method m2(String) in the type Base is not applicable for the arguments (Object)

推荐答案

编译器始终根据调用的引用的声明类型来解析方法调用.

Compiler always resolves the method invocation based on the declared type of the reference you invoke it on.

调用方法时:

base1.m1("");

编译器会以声明的类型base1(在这种情况下为Base)查找方法签名. Base中的匹配方法是:

compiler looks for the method signature in declared type of base1, which is Base in this case. The matching method in Base is:

void m1(Object o) { }

由于参数Object可以接受String参数,因此该调用是有效的.您可以将子类对象传递给超类引用.

Since parameter Object can accept a String argument, the invocation is valid. You can pass a subclass object to a superclass reference.

现在,第二次调用:

base.m2(o);

再次

声明的base类型为Base.而Base类中的匹配方法是:

again the declared type of base is Base. And the matching method in Base class is:

void m2(String o) { }

因为您不能在接受String的地方传递Object引用.编译器会为您提供编译器错误.没有隐式的缩小转换.

Since you cannot pass an Object reference where a String is accepted. The compiler gives you compiler error. There is no implicit narrowing conversion.

通过简单的分配,您可以更清楚地了解它:

You can understand it more clearly with a simple assignment:

Object ob = new Integer(3);
String str = ob;  // This shouldn't be valid

Java不会执行隐式缩小转换.从objstr的分配应该无效,因为否则您将在运行时得到ClassCastException.

Java doesn't perform implicit narrowing conversion. The assignment from obj to str shouldn't be valid, because else you would get a ClassCastException at runtime.

这篇关于无法理解Java中的继承和重写/重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆