J (banana) wrote in java_dev,
J
banana
java_dev

Always something new to learn

It seems that you can override a concrete method and make it abstract. I actually came across some code that did this, so I had to check how it worked. Consider the following:
abstract class Grandfather
{
   protected String speak ()
   {
      return ( "I'm old" );
   }
}

abstract class Father
   extends Grandfather
{
   @Override
   protected abstract String speak ();
}

public class Child
   extends Father
{
   @Override
   protected String speak ()
   {
      return ( "I'm young" );
   }

   public static void main ( final String [] args )
   {
      System.out.println ( new Child ().speak () );
   }
}
It prints "I'm young" (unsurprisingly) but the interesting part is that despite Grandfather defining a speak method, Father is forcing Child to re-implement it. Grandfather's speak method can't be called by Child because Father has made it abstract. I had to test that this worked by commenting out some of the speak methods. It really is the case that Grandfather has an implementation but Father doesn't.
Subscribe
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 0 comments