【发布时间】:2014-08-12 19:29:36
【问题描述】:
我是 java 编程新手,对 stackoverflow 也很陌生。遇到了这个我无法理解的简单代码。请帮我看看它是如何工作的
class Base {
public static void foo(Base bObj) {
System.out.println("In Base.foo()");
if(bObj instanceof Base){
System.out.println("Base instance");
}
bObj.bar();
}
public void bar() {
System.out.println("In Base.bar()");
}
}
class Derived extends Base {
public static void foo(Base bObj) {
System.out.println("In Derived.foo()");
bObj.bar();
}
public void bar() {
System.out.println("In Derived.bar()");
}
}
class Downcast {
public static void main(String []args) {
Base bObj = new Derived();
bObj.foo(bObj);
}
}
现在我明白了
In Base.foo()
Base instance
In Derived.bar()
虽然我知道它是如何进行的base.foo()。但是它是如何派生的。它还打印出它是一个基础对象的实例,然后是如何派生的。给出的解释是,它之前进行了静态解析,后来进行了动态解析。什么是静态的和动态分辨率。
虽然这个概念是这样的
Base b=new Derived();
这意味着我们创建了一个派生对象,然后将其向上转换为 Base。那么为什么不调用 base.bar() 呢?
提前致谢。
【问题讨论】:
-
static方法未被覆盖。如果你在子类中声明了一个static方法,它与父类中的static方法具有相同的签名,则称为隐藏它。 -
你的意思是子类中的静态方法隐藏还是父类?
-
子类方法隐藏父类方法。多态性也不适用于
static方法。
标签: java inheritance base derived-class