为什么 System.out.println(a.g(3));调用的A类中的函数static int g(n)? 该函数在B类中不也是进行了重写嘛
public class A {
double f(double x,double y)
{
return x+y;
}
static int g(int n)
{
return n*n;
}
}
public class B extends A{
double f(double x,double y)
{
double m= super.f(x,y);
return m+x*y;
}
static int g(int n)
{
int m=A.g(n);
return m+n;
}
}
public class E {
public static void main(String[] args) {
B b=new B();
System.out.println(b.f(10.0,8.0));
System.out.println(b.g(3));
A a=new B();
System.out.println(a.f(10.0,8.0));
System.out.println(a.g(3));
}
}
【以下回答由 GPT 生成】
在Java中,方法的调用是根据对象的实际类型决定的,而不是根据对象的声明类型决定的。所以在上述代码中,调用System.out.println(a.g(3))时会执行A类中的函数static int g(n)。
当声明A a = new B();
时,虽然对象a是通过B类实例化的,但是由于a的声明类型是A类,所以编译器会根据声明类型A去寻找匹配的方法。在A类中有一个static int g(int n)方法,所以会执行A类中的该方法而不是B类中的方法。
如果希望执行B类中的方法,可以通过向下转型来实现。将声明类型为A的对象a强制转换为B类的对象,然后再调用方法即可。
修改后的代码如下:
public class E {
public static void main(String[] args) {
B b = new B();
System.out.println(b.f(10.0, 8.0));
System.out.println(b.g(3));
A a = new B();
System.out.println(a.f(10.0, 8.0));
System.out.println(((B) a).g(3)); // 向下转型后调用B类中的方法
}
}
注意,向下转型可能会引发ClassCastException异常,所以在进行向下转型时要确保对象的实际类型与转型的类型匹配。