那为什么上述两段程序可以通过呢?class B 不是覆盖了class A的m()方法吗?

解决方案 »

  1.   

    package overprivate;
    class base1{
      private int i;
      public void seti(){
        set();
      }
      public int get(){
        return i;
      }
      private void set(){
        i=5;
      }
    }
    public class Untitled1 extends base1{
      private int i;
      private void set(){
        i=4;
      }
      public static void main(String[] args) {
        Untitled1 u=new Untitled1();
        base1 b=new base1();
        b.seti();
        u.seti();
       // seti();
        System.out.println("u.i="+u.i+"\nb.i=" +b.get());
     }
    }
    the result is:
    u.i=0
    b.i=5could you tell me why?
      

  2.   

    when i use step debug,i see the base1.set() is executed when object u called method seti().but nothing was changed after base1.set().
    en ,it is an interesting thing if someone could explain how it works for me,thanks.
      

  3.   

    TO purples:javap -c -s -l -classpath . -private Untitled1you will find what's different between base1.seti() and Untitled1.seti()
      

  4.   

    to 搂主:
        程序确实能通过。但不算覆盖。
        private方法对于派生类来说根本不存在(不可见),看都看不到何谈覆盖?他们只是名称一样的两个毫不相干的两个方法,只在各自的类里可见,把他们的名字改成不同也不会对程序产生任何影响。
        static成员不依赖对象而存在,但说static不能继承恐怕不准确。用派生类也可以访问基类的static方法(当然要可见)。关于是不是覆盖,下面说明:class a {
      void m(){
        System.out.println("this is class a");
      };
    }class b extends a {
      void m(){
        System.out.println("this is class b");
      };
    }class text {
      public static void main() {
      a a1 = new b();
      a1.m();
    }结果:
    this is class b
    这是正常的覆盖行为。然后在两个m()前加上static再看一下结果,你会发现:
    this is class a
    静态方法的调用根本不取决于对象的实际类型,而只是声明的类型。
    所以,这也不是覆盖。
      

  5.   

    关于static的,还可以看一下Java Pitfall中的讲解。
      

  6.   

    我看过Java Pitfall中的讲解,挺不错。
    顺便提一下,C#根本不让这样的代码编译。
    C#只允许ACLASS.foo(),不允许aObject.foo().
    使用Java的时候应该避免后者,一些代码分析工具
    比如JTest会告诉你这类错误。
      

  7.   

    Java 中虽然允许使用引用来调用 静态方法,但是这样的做法是应该避免的.
    比如 aObject.foo() 或者 this.foo() 等.看看The Java Programming Language 3rd Edition中关于这一段的描述:
    A static member may also be accessed via a reference to an object of that class, but this form should be AVOIDED as it gives the false impression that static field is a member of the object, not a member of the class.
    It is the type of the reference, not the type of the object it refers to, that determines the class to look in for the static vaiable. The reference can even be NULL.其实有一些集成开发环境(比如IntelliJ-IDEA)已经在帮助我们解决这个问题.使用对象引用的静态域在其编译环境中是不允许的(或者是被警告的).
    功欲善其事,必先利其器.采用一些方便的工具确实是有很大的好处的.
      

  8.   

    看看think in java,里面对这个讲得很详细