0
// file name: Main.java 
class Base { 
    private void foo() {
        System.out.printf("Message");
    } 
} 

class Derived extends Base { 
    public void foo() {
        System.out.printf("Message1");
    } // works fine 
} 

public class Main { 
    public static void main(String args[]) { 
        Base d = new Derived(); 
        d.foo();
    } 
} 

when I write Derived d=new Derived() it works fine but when i write Base d =new Derived() it gives error of private function cannot be overrided.

Khalid Shah
  • 3,132
  • 3
  • 20
  • 39
Saurav
  • 15
  • 7

3 Answers3

1

I don't know why you say "It gives error of private fn cannot be overrided" - that's not the error you get when you try to compile this. It gives the following error instead:

$ javac Main.java
Main.java:16: error: foo() has private access in Base
        d.foo();
        ^
1 error

Why: Because foo() is a private method in class Base, so you cannot call it on a variable of type Base.

Also: You can indeed not override private methods; in fact, the foo() method in class Derived is a method that is completely separate from the foo() method in class Base, that just happens to have the same name. It does not override the method in class Base.

Jesper
  • 202,709
  • 46
  • 318
  • 350
0

This is because foo is private in Base class. You can use public or protected

Sodala
  • 300
  • 1
  • 7
0

The method you want to inherit is private. So you don't override it. You hide it instead. So Base.foo and Derived.foo are completely different methods.

Note: hiding private methods is valid

I would suggest you to use @Override annotation on methods you override. It will prevent you from hiding private methods.

ETO
  • 6,970
  • 1
  • 20
  • 37