Method Overriding (Cont.)


Overriding and Access Modifiers
The access modifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass. Doing so, will generate compile-time error.

Modifiers.java (overriding and access modifiers)
// Demonstration of overriding and access modifiers 
class Modifiers {
  public static void main( String[ ] args ) {
    Parent obj1 = new Parent( );
    obj1.m2( );
    System.out.print( " " );
    Parent obj2 = new Child( );
    obj2.m2( );
  }
}

class Parent { 
  // private methods are not overridden 
  private   void m1( ) { System.out.print( "p.m1" ); } 
  protected void m2( ) { System.out.print( "p.m2" ); } 
} 

class Child extends Parent { 
  // New m1() method, unique to Child class 
  private void m1( ) { System.out.print( "c.m1" ); } 
  // Overriding method with more accessibility 
  @Override
  public  void m2( ) { System.out.print( "c.m2" ); } 
  // The following command causes compilation error:
  // attempting to assign weaker access privileges; was protected
  // private  void m2( ) { System.out.print( "c.m2" ); }
}
shell> java Modifiers  ⇒  Output:           Result:

Final Methods not Being Overridden
If we don’t want a method to be overridden, we declare it as final.
// final methods not being overridden 
class Parent { 
  // Can't be overridden. 
  final void show( ) {  } 
} 
class Child extends Parent { 
  // This would cause error.
  void show( ) {  } 
}




      I don’t have a carbon footprint.    
      I just drive everywhere.