[ACCEPTED]-Change the access modifier of an overridden method in Java?-overriding

Accepted answer
Score: 29

Java doesn't let you make the access modifier 20 more restrictive, because that would violate the rule that 19 a subclass instance should be useable in 18 place of a superclass instance. But when 17 it comes to making the access less restrictive... well, perhaps 16 the superclass was written by a different 15 person, and they didn't anticipate the way 14 you want to use their class.

The programs 13 people write and the situations which arise 12 when programming are so varied, that it's 11 better for language designers not to "second-guess" what 10 programmers might want to do with their 9 language. If there is no good reason why 8 a programmer should not be able to make access 7 specifiers less restrictive in a subclass 6 (for example), then it's better to leave 5 that decision to the programmer. They know 4 the specifics of their individual situation, but 3 the language designer does not. So I think 2 this was a good call by the designers of 1 Java.

Score: 7

Extending a class means the subclass should 6 at least offer the same functionality to 5 the other classes.

If he extends that, then 4 it is not a problem.

Extending could be be 3 either adding new methods or by offering 2 existing methods to more classes like making 1 a package-access method public.

Score: 6

There is only one, you might want the override 2 to be visible by more classes, since no 1 modifier is default, public broadens that.

Score: 3

The explaination is this:-

It's a fundamental 12 principle in OOP: the child class is a fully-fledged 11 instance of the >parent class, and must 10 therefore present at least the same interface 9 as the parent class. >Making protected/public 8 things less visible would violate this idea; you 7 could make child >classes unusable as 6 instances of the parent class.

 class Person{
 public void display(){
  //some operation

class Employee extends Person{
private void display(){
   //some operation

 Person p=new Employee();

Here p is 5 the object reference with type Person(super 4 class),when we are calling >p.display() as 3 the access modifier is more restrictive 2 the object reference p cannot access child 1 object of type Employee

Score: 1

Edit: OK, I changed my answer to fix the problem.

If that couldn't be done, then there would 4 be some cases where a class wouldn't be 3 able to implement an iterface and extend 2 a class because they have the same method 1 with different access modifiers.

public Interface A {
  public void method();

public abstract classs B {
  protected void method();

public class AB extends B implements A {
   * This would't be possible if the access modifier coulnd't be changed
   * to less restrictive
  public void method();

More Related questions