0

I am having difficulties understanding why i get errors with the following code and then not in the other case:

SCENARIO 1 (has error)

class App{
public  static void main(String[]args) {
    ClassA a = new ClassB();
    a.print();  
    }
}

class ClassA {       
    protected void print() {}   
}

class ClassB extends ClassA {
     void print(){}
     //creates error: Cannot reduce the visibility of the inherited method from ClassA
}

SCENARIO 2 (No errors)

class App{
public  static void main(String[]args) {
    ClassA a = new ClassB();
    a.print();  
    }
}

class ClassA {       
    protected void print() {}   
}

class ClassB extends ClassA {        
    protected void print(){}
     //no error/ Override method
}

Any help much appreciated.

Jeremy Levett
  • 939
  • 9
  • 13
  • package private has a lower visibility than `protected`, that´s what the compiler is hinting you at, you reduce the visibility, by ommiting the `protected`, which is not allowed. – SomeJavaGuy Nov 21 '17 at 11:32

2 Answers2

2

Default access modifier (no keyword) is more restrictive than the protected access modifier, meaning when a method has a protected access modifier it's only visible to classes in the same package and sub-classes. On the other hand, (no keyword) access modifier is accessible only for classes in the same package. Another thing that you have to know, is one of the overriding rules is that the overridden method must have the same or less-restrictive access modifier.

Rules of overriding a method:

  1. Only inherited methods are overridden
  2. Method in child must have the same signature as the method in the parent
  3. Final, private and static methods cannot be overridden
  4. Must have the same return type or sub-type
  5. Access-modifier must be less-restrictive than the one in the parent
  6. Must not throw new or broader checked exceptions
Ahmad Sanie
  • 3,678
  • 2
  • 21
  • 56
0

Your error message pretty much explains why it doesn't work. The default access modifier is more restrictive than the protected access modifier. This will give you problems if you would try the following from a context where you would have access to print(i.e. in a subclass of ClassB):

ClassA myClassA = new ClassB();
myClassA.print();

print on ClassA would be accessible in this subclass, but if you would allow an override with a more restrictive access modifier (i.e. default or private) that wouldn't work.

Rob Obdeijn
  • 253
  • 2
  • 9