java - 类型检查和方法查找

标签 java

我对 Java 中类型检查和方法查找的功能感到困惑。

据我了解,类型检查是在编译时完成的,方法查找是在运行时完成的。

类型检查基于引用对象的声明类型,而方法查找基于引用的实际类型。

因此假设 MyInt 类是 GaussianInt 类的父类(super class),如下所示:

class MyInt 
{ 
    private int n; 
    public myInt(int n)
    { 
        this.n = n;
    }
    public int getval()
    {
        return n;
    }
    public void increment(int n)
    { 
        this.n += n;
    }
    public myInt add(myInt N)
    { 
        return new myInt(this.n + N.getval());
    }
    public void show()
    { 
        System.out.println(n);
    }
}

class GaussInt extends MyInt 
{ 
    private int m; //represents the imaginary part
    public GaussInt(int x, int y)
    { 
        super(x); 
        this.m = y;
    }
    public void show()
    { 
        System.out.println( "realpart is: " + this.getval() +" imagpart is: " + m);
    }
    public int realpart() 
    { 
        return getval();
    } 
    public int imagpart() 
    {
        return m;
    }
    public GaussInt add(GaussInt z)
    { 
        return new GaussInt(z.realpart() + realpart(), z.imagpart() + imagpart()); 

}

假设在 main 方法中我们有以下内容:

GaussInt z = new GaussInt(3,4); 
MyInt b = z;
MyInt d = b.add(b)
System.out.println("the value of d is:"+ d.show());

print语句中的show语句中到底会使用哪种add方法?

据我了解,b被声明为MyInt,但实际上它是GuaussInt。类型检查器只看到 b 是 MyInt 类型并且它具有 add(MyInt),因此代码有意义并可以编译。

但是在运行时,方法查找发现 b 是 GaussInt 类型,并且它有两个 add() 方法,因此它将通过查看方法签名来使用 add(GaussInt) 方法,并生成一个 GaussInt。但是d是MyInt类型,方法查找会认为不行,那会不会又回到add(Myint)呢?

程序编译和运行背后的机制是如何工作的?

最佳答案

From what I understand, b is declared to be MyInt, but it is, in fact, GaussInt

正确b 的引用类型是 MyInt,但它指向 GaussInt 类型的对象。

But then in run time, the method lookup sees that b is of type GaussInt and it has two add() methods, so it will use add(GaussInt) method by looking at method signature and it produces a GaussInt. But d is of type GaussInt and method lookup will think it won't work, then will it go back to add(Myint)?

由于 GaussInt 中的 add 方法采用的是 GaussInt 类型的引用,而不是 MyInt 类型的引用。所以b.add(b)会调用MyInt类型的add方法。由于 gaussInt 有两种 add 方法,一种采用 MyInt 类型的参数,另一种采用 GaussInt 类型的参数。所以它会调用myInt(superclass)add方法。

您想要实现的目标是方法重写。为了让它工作,方法签名应该相同。也就是说,父类方法和子类方法在各个方面都应该匹配,除了子类方法的返回类型可以是父类方法的返回类型的subtype

为了实现你所提到的,即b.add(b)应该调用gaussIntadd方法,< strong>使两个类中add方法的参数类型相同。

您还应该了解动态多态性(运行时检查)和静态多态性(编译时类型检查)。

关于java - 类型检查和方法查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55540618/

相关文章:

java - 边框布局不起作用?

java - 将 JSON 解析为 java 对象

Java 错误 "exception in thread"

java - 图像未显示在窗口上

java - 使用Optional.ofNullable()简化条件

java - 我可以在 jspx 文件中使用 jsp scriptlet 吗?

java - 使用 lambda 和流按值对 map 进行排序

java - Thymeleaf 选择标签导致异常

javaice4j与nist-sdp包冲突

Java 模式创建对象