简体   繁体   中英

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

Can private methods be overridden in 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(); . 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:

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. 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 has no knowledge Base's implementation of func() since its declared as private. 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() . To be clear: it would be incorrect to say you are overriding Base's implementation of 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() . A s implementation of doStuff() is fixed to calling A#getStuff() , no polymorphism will be triggered.

Nope because if you do something like Base b = new Derived(); you still won't be able to call 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

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. 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 . 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.

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'.

      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()); } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM