-
January 30th, 2012, 09:11 AM
#1
How to override a method in Java, but still have partial functionality of the parent
This question was asked during job interview, Java Development, student position.
interface someInterface
{
}
class A implements someIterface
{
}
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...
-
January 30th, 2012, 10:49 AM
#2
Re: How to override a method in Java, but still have partial functionality of the par
Your description of what is required is not clear so I'm just going to answer the question asked in the subject line. ie
How to override a method in Java, but still have partial functionality of the parent
You just call super.xxx() to run the code in the parent method, where xxx is the name of the overridden method.
Note: You should call the method execute() and not Execute() as the Java naming convention is for method names to begin with a lower case letter.
-
January 30th, 2012, 01:15 PM
#3
Re: How to override a method in Java, but still have partial functionality of the par
Thank for the answer, but it is not what I look for actually.
I will try to explain it again:
class A implement an interface, and class B extended class A. Class B has an method "execute" that do something. The question is what I should to do in order to get an output "process start" when I call to "execute" method, of course this output should be not written in the method "execute" it self, after our required output the method should be executed as it implemented in class B.
obj.execute();
out put:
"process start"
"some other output"
thanks in advance.
-
January 30th, 2012, 01:45 PM
#4
Re: How to override a method in Java, but still have partial functionality of the par
If you want to output something when execute() is called but before the code in class B's execute() method is run then you have to extend class B and override the execute() method. This new class then prints the required output and calls super.execute().
You can do this by creating a new class C or when you instantiate class B ie
Code:
B myObjectB = new B() {
@Override
public void execute() {
System.out.println("process start");
super.execute();
}
};
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|