- We can not override private methods in java.
- The basic inheritance principle is when we are extending a class we can access all non private members of a class so private members are private to that class only we can not access anywhere outside the class if we declare anything as private.
- Know more information about access specifiers here
- Class A{
- int a;
- private int b;
- public void print(){
- System.out.println("print method of super class A");
- }
- private void add(){
- System.out.println("add method of super class A");
- }
- }
- Class B extends A{
- public void show(){
- System.out.println("show method of sub class B");
- }
- public static void main(String[] args){
- B obj= new B();
- obj.a=30;
- obj.print();
- obj.show();
- System.out.println("a="obj.a);
- //obj.b=20; compile time error. The field Super.a is not visible
- //obj.add(); compile time error : The method show() from the type Super is not visible
- }
- }
Output:
- print method of super class A
- show method of sub class B
- 30
- From the above program we can say super class private members are not accessible to sub class.
- lets see what will happen if we try to override a method of super class?
- Sorry if we are unable to access super class private methods then there should not be a questions of overriding that method right?
- Yes private methods of super class can not be overridden in sub class.
- Even if we try to override same method of super class that will became a sub class own method not overridden method.
- Class A{
- int a;
- private int b;
- private void add(){
- System.out.println("add method of super class A");
- }
- }
- Class B extends A{
- private void add(){
- System.out.println("add method of sub class B");
- }
- public static void main(String[] args){
- B obj= new B();
- obj.a=30;
- obj.add();
- System.out.println("a="obj.a);
- }
- }
Output:
- add method of sub class B
- 30
- We can prove this by providing @override annotation in sub class method
- Class A{
- int a;
- private int b;
- private void add(){
- System.out.println("add method of super class A");
- }
- }
- Class B extends A{
- //@override
- private void add(){// if we place @override annotation compile time error will come here
- System.out.println("add method of sub class B");
- }
- public static void main(String[] args){
- B obj= new B();
- obj.a=30;
- obj.add();
- System.out.println("a="obj.a);
- }
- }
Output:
- add method of sub class B
- 30
No comments