覆盖私有方法和可见性

时间:2014-07-31 14:36:58

标签: java override private-methods

我知道私有方法隐藏在Derived类中,并且它们无法被覆盖,但我的问题是不同的。请解决以下问题。我的问题在下面提到的问题中提到:

TestPolymorphism.java

class CheckParent {
    private void display() {
        System.out.println("This is parent class");
    }
}

class CheckChild extends CheckParent {
    void display() {
        System.out.println("This is child class");
    }
}

public class TestPolymorphism  {
    public static void main(String[] args) {
        CheckParent cp = new CheckChild();
        cp.display();        // This will throw error as display() method id private
        //  and invisible to child class
    }

但是,在以下代码段中,不会抛出任何异常。

CheckParent.java

  public class CheckParent {
       private void display() {
            System.out.println("This is parent class");
        }
        public static void main(String[] args) {
            CheckParent cp = new CheckChild();

            cp.display();   /*This will print "This is parent class" without any error
            * my question is why no error is thrown like above case
            * as here too display() method is private and invisible to
            * derived class */
        }
    }

    class CheckChild extends CheckParent {
        void display() {
            System.out.println("This is child class");

        }
    }
}

2 个答案:

答案 0 :(得分:1)

对于构造函数,private,final或static方法,使用静态(早期)绑定。对于所有其他使用动态(后期)绑定。看看这个:

http://geekexplains.blogspot.co.uk/2008/06/dynamic-binding-vs-static-binding-in.html

答案 1 :(得分:0)

如果要覆盖父类方法,请考虑将@Override注释放在重写方法的前面,以便编译器可以警告您可能出现的错误。

我认为您不会使用子类的display()方法覆盖父类的display()方法,因为父类的方法是private。你宁愿定义一个新方法。

class CheckParent {
    //remove private access modifier to have the method overriden in child class
    private void display() {
        System.out.println("This is parent class");
    }
}

class CheckChild extends CheckParent {
    @Override //IDE or compiler will warn you that you are not overriding anything        
    void display() {
        System.out.println("This is child class");
    }
}

请参阅Bloch的Effective Java. 2nd Edition,第36项。

在第二个代码片段中,您创建了CheckChild实例,但store是CheckParent,在CheckParent类的private void display()方法中访问CheckParent实例方法的static。类成员(在您的情况下为静态方法)可以访问它的私有方法和字段,因此此代码有效。

如果要在第二个代码段中访问CheckChild类实例的实例void display()方法,则应首先将CheckParent实例强制转换为CheckChild。

public class CheckParent {
    private void display() {
        System.out.println("This is parent class");
    }
    public static void main(String[] args) {
        CheckParent cp = new CheckChild();
        cp.display();   //"This is parent class"

        if (cp instanceof CheckChild){
            ((CheckChild) cp).display(); //"This is child class"
        }
     }
}
class CheckChild extends CheckParent {
    void display() {
        System.out.println("This is child class");
    }
}

无论如何,这种编码方法看起来像是对我的滥用。