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...
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:
execute
instead of Execute
SomeInterface
instead of someInterface
execute
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With