Wednesday, October 23, 2013

What happens when we write weaker access privileges for a overridden method compare to super class method?



This is an Interview question, This question raises while asking questions in corejava.

- While overriding any method, we must not write weaker privileges than the parent. If we write, we will get compilation error.


Take an example

A.java
public class A{
      public void go(){}
}

B.java
public class B extends A{
       public void go(){}
}

If we compile the above code, we don't get any compilation error and compiles successful.


Suppose change the access specifier of B's go() method to protected or private or default.

B.java
public class B extends A{
     protected void go(){}  --------->   compilation error
}


we will get compilation error stating that ...

error:
go() in B cannot override go() in A; attempting to assign weaker access privileges; was public
protected void go(){}
              ^
1 error

----------------------------------------------------------------------------------------------------------------------------

And one more thing we have to remember that we also cannot override private method...

example:

public class A{

        private void go(){
         }
}
public class B extends A{

        private void go(){ //It compiles successfully, but Its not overridding..
         }
}

How:
- If we write annotation in class B's go() method as @Override, Then the compiler will give us error,
- So, we cant override private methods...

No comments:

Post a Comment