Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a method in Java, but still have partial functionality of the parent method

This question was asked during job interview, Java Development, student position.

interface SomeInterface {
    public void execute();
}

class A implements SomeInterface {
    public void execute() {...}   
}

The question is:

New developer was asked to create a class that extends class A, and create method named Execute, this method will do some thing. How we should to rewrite the above code in order to have an output "start process" when method Execute is called (of course the printing should not be done in class B).

class B extends A {
   public void execute() {
      //some code goes here 
   }
}

I know that it can be done with two functions and one of them is abstract. Please advise...

like image 624
Victor Avatar asked Jan 30 '12 12:01

Victor


2 Answers

This is an example of the template pattern. The abstract super Class A imposes the structure to processing by doing the "standard" parts - in this case printing something - and then invokes the concrete implementations of the subclass to do the actual/specific processing:

abstract class A implements someIterface {
   public void Execute() {
      System.out.println("start process"):
      doExecute();
   }

   protected abstract void doExecute();
}

class B extends A {
    protected void doExecute() {
        // some code goes here
    }
}

It would be more usual for:

  • The method to be called execute instead of Execute
  • The interface to be called SomeInterface instead of someInterface
  • The interface to have the method execute
like image 98
Bohemian Avatar answered Oct 19 '22 04:10

Bohemian


super calls the functionality from your parent class.

public class Test
{
    public static void main(String[] args)
    {
        B b = new B();
        b.execute();
    }
}

interface Foo
{
    public void execute();
}

class A implements Foo
{
    public void execute()
    {
        System.out.println("from class A");
    }
}

class B extends A
{
    public void execute()
    {
        super.execute();
        System.out.println("from class B");
    }
}

The output of this code is

from class A
from class B
like image 36
Ross Avatar answered Oct 19 '22 02:10

Ross