简体   繁体   English

可以在子类中重写超类中的私有方法吗?

[英]Can a private method in super class be overridden in the sub-class?

Can private methods be overridden in Java? 可以在Java中覆盖私有方法吗? If no, then how does the following code work? 如果不是,那么以下代码如何工作?

class Base{
      private void func(){
            System.out.println("In Base Class func method !!");         
      };
}

class Derived extends Base{
      public void func(){   //  Is this a Method Overriding..????        
            System.out.println("In Derived Class func method"); 
      }      
}

class InheritDemo{
      public static void main(String [] args){                      
            Derived d = new Derived();
            d.func(); 
      }
}

No, you are not overriding it. 不,你没有压倒它。 You can check by trying to mark it with @Override , or by trying to make a call to super.func(); 您可以尝试使用@Override标记它,或尝试调用super.func(); . Both won't work; 两者都行不通; they throw compiler errors. 他们抛出编译错误。

Furthermore, check this out: 此外,检查出来:

class Base {
      private void func(){
            System.out.println("In base func method");         
      };
      public void func2() {
          System.out.println("func2");
          func();
      }
}

class Derived extends Base {
      public void func(){   //  Is this an overriding method?
            System.out.println("In Derived Class func method"); 
      }
}

class InheritDemo {
      public static void main(String [] args) {
            Derived D = new Derived();
            D.func2(); 
      }
}

It will print: 它将打印:

func2
In base func method

When you change func() in Base to public, then it will be an override, and the output will change to: 当您更改func()Base对公众, 那么这将是一个覆盖,输出将变为:

func2
In Derived Class func method

No, a private method cannot be overridden because the subclass doesn't inherit its parent's private members. 不,不能覆盖私有方法,因为子类不继承其父级的私有成员。 You have declared a new method for your subclass that has no relation to the superclass method. 您已为子类声明了一个与超类方法无关的新方法。 One way to look at it is to ask yourself whether it would be legal to write super.func() in the Derived class. 查看它的一种方法是问自己在Derived类中编写super.func()是否合法。 There is no way an overriding method would be banned from accessing the method it is overriding, but this would precisely be the case here. 没有办法禁止重写方法访问它覆盖的方法,但这恰恰就是这种情况。

No, it is not. 不它不是。 You can mark an override just to make sure like this: 你可以标记一个覆盖只是为了确保这样:

@Override
public void func(){
     System.out.println("In Derived Class func method"); 
}

And in this case it would be a compiler error. 在这种情况下,它将是编译器错误。

You are not overriding. 你不是压倒一切。 You cannot override private members, you are merely defining a new method in Derived. 您不能覆盖私有成员,您只是在Derived中定义一个新方法。 Derived has no knowledge Base's implementation of func() since its declared as private. Derived没有知道Base的func()实现,因为它声明为私有。 You won't get a compiler error when you define func() in Derived but that is because Derived does not know Base has an implementation of func() . 在Derived中定义func()时不会出现编译器错误,但这是因为Derived不知道Base有func()的实现。 To be clear: it would be incorrect to say you are overriding Base's implementation of func() . 要明确:说你覆盖Base的func()实现是不正确的。

In addition to the already correct answer, consider this: 除了已经正确的答案,请考虑以下事项:

public class Private {
    static class A {
        public void doStuff() {
            System.out.println(getStuff());
        }

        private String getStuff() {
            return "A";
        }
    }

    static class B extends A {
        public String getStuff() {
            return "B";
        }
    }

    public static void main(String[] args) {
        A a = new A();
        a.doStuff();
        a = new B();
        a.doStuff();
        B b = new B();
        b.doStuff();
    }
}

This will print 这将打印

A 一个

A 一个

A 一个

although B "overrides" getStuff() . 虽然B “覆盖”了getStuff() A s implementation of doStuff() is fixed to calling A#getStuff() , no polymorphism will be triggered. A中的实现doStuff()被固定在调用A#getStuff()没有多态性将被触发。

Nope because if you do something like Base b = new Derived(); 不,因为你做了像Base b = new Derived(); you still won't be able to call b.func(). 你仍然无法调用b.func()。 What you're doing is called "hiding". 你正在做的事情被称为“隐藏”。

Since the method is private it is not visible to the other classes.Hence the derived class does not inherit this method. 由于该方法是私有的,因此其他类不可见。因此派生类不会继承此方法。 So this is not the case of overriding 所以这不是压倒一切的情况

Method hiding will be happening here instead of overriding. 方法隐藏将在这里发生而不是覆盖。 like what happens in case of static. 就像静电一样。

Actually,you are not overriding.Before Java5 实际上,你并不是压倒一切。在Java5之前

an overridden method's return type must match with parent class's method. 重写方法的返回类型必须与父类的方法匹配。

But Java 5 introduced a new facility called covariant return type.You can override a method with the same signature but returns a subclass of the object returned. 但Java 5引入了一个名为covariant返回类型的新工具。您可以使用相同的签名覆盖方法,但返回返回的对象的子类。 In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass. 换句话说,子类中的方法可以返回一个对象,该对象的类型是由超类中具有相同签名的方法返回的类型的子类。 you can follow this thread : Can overridden methods differ in return type? 你可以遵循这个主题: 可以覆盖的方法在返回类型上有所不同吗?

A private method can never be over ridden. 私有方法永远不会被过度使用。 It is always hidden. 它总是隐藏的。

In your example - Derived class has one parent class private method and has its own function func . 在您的示例中 - Derived类具有一个父类私有方法,并且具有自己的函数func Both are different, and the func is not over ridden. 两者都不同, 功能也不会过度。 Its a separate independent function. 它是一个独立的独立功能。

If you create a new function in parent class calling parent class function, the parent func will be called, if parent class reference is used as opposed in the case of method over ridding 如果在父类中调用父类函数创建一个新函数,则将调用父函数,如果使用父类引用,则在方法超出的情况下使用父函数

Note : An object defines the members which it has, and a reference defines which it can access 注意 :对象定义它拥有的成员,引用定义它可以访问的成员

// Method Over ridding case //方法超越案例

class Base{
      public void func(){
            System.out.println("Parent class");         
      };                                                                   
      public void func1(){                                                
            func();                                                             
       }                                                                        
 }

class Derived extends Base{
      public void func(){         
            System.out.println("Derived class"); 
      }      
}

class InheritDemo{
      public static void main(String [] args){                      
            Derived d = new Derived();                               
            d.func1(); // Prints Derived class                                          

            Base b = new Derived();                                    
            b.func1();                                                         // Prints Derived class - no matter parent reference is calling,as there as method is overridden - Check func1() is in parent class, but id doesn't call parent class func() as the compiler finds a func() method over ridden in derived class    

      }
}

// Method Hidding case - Private and static methods case  

class Base{
      private void func(){
            System.out.println("Parent class");         
      };                                                                   
      public void func1(){                                                
            func()                                                              
      }     
}

class Derived extends Base{
      public void func(){   //  Is this a Method Overriding..????        
            System.out.println("Derived class"); 
      }      
}

class InheritDemo{
      public static void main(String [] args){                      
            Derived d = new Derived(); 
            d.func1(); // Prints Derived class
            Base b = new Derived();
            b.func1(); 
// Prints Parent class - the reason is we are using the parent class reference, so compiler is looking for func() and it founds that there is one private class method which is available and is not over ridden, so it will call it. Caution - this won't happen if called using derived class reference.

            b.func();
// this prints the Derived class - the compiler is looking func(), as Derived class has only one func() that it is implementing, so it will call that function. 

      }
}

The private member of the base class cannot be access by anyone outside of the class and cannot be overridden. 基类的私有成员不能被类外的任何人访问,也不能被覆盖。 The function in the derive class is an independent function that can be access by anywhere. derive类中的函数是一个独立的函数,可以在任何地方访问。

The code would run the function in the derived class 代码将在派生类中运行该函数

Read comments in the below code snippet to find the answer. 阅读以下代码段中的注释以查找答案。

Sources: 资料来源:

  1. Definition reference: 定义参考:

  2. Credits for the source code example(reference) from the book - "OCA Oracle Certified Associate Java SE 8 Programmer Study Guide Exam 1Z0-808 Book" from 'Jeanne Boyarsky' and 'Scott Selikoff'. 来自“Jeanne Boyarsky”和“Scott Selikoff”的书中的“OCA Oracle认证助理Java SE 8程序员学习指南考试1Z0-808书籍”中的源代码示例(参考)的学分。

      public class Deer { public Deer() { System.out.print("Deer"); } public Deer(int age) { System.out.print("DeerAge"); } private boolean hasHorns() { return false; } public static void main(String[] args) { Deer deer = new Reindeer(5); System.out.println(","+deer.hasHorns());// false is printed. } } class Reindeer extends Deer { public Reindeer(int age) { System.out.print("Reindeer"); } private boolean hasHorns() { return true; } // Overriding possible, but is of no use in the below context. // Below code is added by me for illustration purpose public static void main(String[] args) { Deer deer = new Reindeer(5); //Below line gives compilation error. //System.out.println(","+deer.hasHorns()); } } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java中,为什么超类方法不能从子类实例访问受保护的或私有的方法/变量? - In Java, why can't a super-class method access protected or private methods/variables from a sub-class instance? 子类和超类中finalize方法的行为 - behavior of finalize method in sub-class and super-class 将子类传递给方法但将超类作为参数? - Passing in a sub-class to a method but having the super class as the parameter? 当引用类型为超类时,子类无法访问超类的受保护方法 - Sub-class not able to access the protected method of super-class when the reference is of type super-class 当子类的实例不可见时,为什么要在该子类的实例上调用私有方法? - Why can I invoke a private method on an instance of the sub-class when it shouldn't be visible to the instance? 使用重写的抽象方法从超类访问私有变量 - Accessing private variables from a super class using an overridden abstract method 重载重载方法是重载父类还是子类方法 - Overloading overridden method am I overloading parent or sub-class method 如何确保从子类(Java)中的方法在抽象超类中调用某些方法 - How to ensure a certain methods gets called in abstract super-class from method in sub-class (Java) 从超类调用方法,但在Java中使用子类的局部变量 - Calling a method from the super-class but using a local variable from the sub-class in java Java泛型能否将2个不同子类的列表合并为一个超类列表? - Can Java generic merges 2 lists of different sub-class into one list of super class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM