I have a class Writer which has a method process(). A subclass, TextWriter, extends Writer.
I want to use the method process() of the parent class, except for the last line of the method, which I want to customize according to the needs of the subclass.
Is there any way I can call super() in such a way that I can inherit only specific parts of the parent class's method?
I know this is bad design, and in such cases interfaces must be used. But I was working on making some changes on some old code, and I was wondering if it is possible to do this.
You should put the joint code in a protected method and have the process method call it, like:
public class Writer {
protected void process_subProcess(){
//most of process code
}
public void process(){
process_subProcess();
//specific last line
}
}
Then TextWriter only overrides the bit it needs to. subProcess isn't a great name, consider a better one depending on what the subProcess actually does
public class TextWriter extends Writer{
#Override
public void process(){
process_subProcess();
//different final line
}
}
The joint code is protected so that child classes can access it but you can't accidentally use the subProcess method from outside the package
No, this is not possible in Java.
If you have control over the parent class, you can refactor it to ensure the relevant parts can be overriden. If not, you don't really have another option.
No, but you can extract the part that differes between both classes to another methode which you implement differently in each class.
No, You cann't override a certain piece of code. overriding is related to the method not to some line of code
No you can't do that.
Best way is override that method in your child class and do your specific work.
Related
I am running into the trouble of extending/altering private methods in subclasses. For instance, I am creating a mock object that inherits from a super class in order to be used in testing.
Here is an example of the code from the parent class that I would like to alter:
private void build(int skill) {
// switch screen
state = Constants.STATE_GENERATING;
percentdone = 0;
notifyViewerRedraw() ;
// select generation method
switch(method){
case 1 : mazebuilder = new MazeBuilderPrim(); // generate with Prim's algorithm
break ;
case 0: // generate with Falstad's original algorithm (0 and default), note the missing break statement
default : mazebuilder = new MazeBuilder();
break ;
}
}
I know that private methods cannot be overwritten in subclasses. So therefore I should create a new method of the same signature. Would I also have to recreate all the private variables in this class too? But if I do that, I am unsure if that would change the behavior to be different from the parent class since the I know that space is actually reserved for private variables from the parent class in the subclass. Therefore, I would have duplicate private variables. I don't know what the best way is to approach this.
If you find the need to override a method in a subclass, perhaps the logic that method is responsible for is abstract enough to warrant a public or protected method.
Consider the design of the Strategy Pattern. Basically, there shouldn't be a need to override a private method, because those methods should be reserved for things outside your interface and only specific to that particular concrete class.
Something as integral and specific as build() to me sounds like it belongs as a protected method which your highest superclass may use at some point during construction but which shouldn't be called externally. Of course, if it's safe to call build() as many times as necessary (idempotent), like a render() method might be in a game character class, then it should be safe to make it public and document what your expectations are of its implementation.
Try using mocking API, for example Jmockit .
Using it, will save you a lot of trouble doing hand mocks, like in your case extending class with private methods! Good luck.
Im not sure how your program works overall but it might be worth you looking into abstract classes and methods if you want all of the base classes to share the same methods(?)
You can call super() in the subclasses method which will call the superclasses method and then make the extra changes you need in the subclasses method.
Edit: Read the original question wrong. If a method has functionality in the superclass and you want to extend or alter it, you shouldn't set it to private. Protected is probably the best bet in your case, as it allows subclasses to extend it using super() or just override it.
I have recently stubled upon something that has always annoyed me.
Whenever I want a method to be invoked in all classes that have a certain interface, or if they are extensions, I would like to have a keyword that does the opposite of the keyword super. Basically, I want the invocation to be passed down (if a class inherits a method, and the method in the superclass is called, it will be called in the subclass as well). Is there anything that resembles what I am asking for?
EDIT:
The contemporary methods I am using are efficient, but not as efficient as I would like them to be. I am only wondering if there is a way of invoking a method, that has been inherited, from its superclass/superinterface. The last time I was looking for this, I did not find it either.
NOTE: All of the subclasses are unknown, hence impossible to utilize. The only known class is the superclass, which is why I can't invoke it. This can be solved using the Reflections API, which I am currently using. However, it does not always comply with what I am searching for.
Every method in Java is virtual with the exception of static methods, final methods and constructors meaning that if a subclass implements the method being invoked, the subclass's implementation will be called. If the subclass wishes to also invoke the immediate superclass method, that is accomplished via a call to super.
This is very common with abstract classes where some base class is utilized by a framework, but clients are expected to override. For instance:
public abstract class Drawer{
public void draw(){
//setup code, etc common to all subclass implementations
doDraw();
}
protected abstract void doDraw();
}
public class CircleDrawer extends Drawer{
protected void doDraw(){
//implementation of how to actually draw a circle
}
}
Now, when you have an instance of CircleDrawer and you call draw(), the superclass Drawer.draw() method will be invoked that is, in turn, able to call CicleDrawer.doDraw().
Edit Now, if CircleDrawer was this:
public class CircleDrawer extends Drawer{
public void draw(){
//do stuff
}
protected void doDraw(){
//implementation of how to actually draw a circle
}
}
Any invocation of Drawer.draw() on an instance of CircleDrawer will always invoke the CircleDrawer.draw() method.
If you mean something like this:
class A {
public void func1(){
//do stuff
subclass.func1();
}
}
class B extends A{
public void func1(){
//do more stuff
}
}
class C extends A{
}
What happens when I call new C().func1()? Remember, func1 is not abstract and therefore, you cannot require classes to define it.
A better solution is to do the following:
abstract class A {
public void func1(){
//do stuff
func2();
}
public abstract func2();
}
class B extends A{
public void func2(){
//do more stuff
}
}
Hence, you require your subclasses to define a function that you can call from the super class.
The is no such a thing. When calling an overriden method in Java, the child-most class's method will be always called. If you want to call parent methods as well, you need to use super.methodCall() in every class's method of your hirearchy.
Unfortunately, I don't believe the thing you are trying to do is as possible as you may think. It's not quite that easy to invoke your subclasses from the super class, because not all subclasses may behave in the same way so a generic keyword for that functionality would wreak havoc! Although, by the phrasing of "Basically, I want the invocation to be passed down." it sounds like what you want is normal inheritance.
Just define the most generic similarities that all subclasses have in common in the superclass, then simply start each subclass definition of the method with super()
I don't mean to point out the obvious, but OO was designed for that and not for what you are asking. I doubt you'll be unable to find a way to do what you want within the typical arsenal of OO concepts
I think you got confused describing what you need, I don't think this:
Whenever I want a method to be invoked in all classes that have a certain interface, or if they are extensions
Is the same as this:
I would like to have a keyword that does the opposite of the keyword super
From what I understand, in the first one, you are referring to calling a method for all instances of a base class and its subclasses. For the second one, calling a subclass' method is exactly calling that method on a subclass which has probably overriden it.
I'm not sure what you are trying to do, maybe you should clarify with an example. Most likely, yours is a design problem which is solved in a different way than the one you are proposing. However, a "solution" came to mind when reading your question.
I'm a little more experienced with C# and python than with Java (and not even that much), but I'm sure more experienced programmers won't hesitate to correct me if I said stupid things.
You should have some kind of collection of objects of type of the base class and call that method, on each object, which each subclass must have overriden.
Maybe using the observer pattern, which is commonly used to reproduce event triggering, you can make all instances of a base class and its subclasses execute a "callback" whenever you want.
I have a class called Base which has a method called execute(). There are about 100 classes which derive from this base class and provide their own implementation of execute(). Now, I have some common logic which I want to put in Base.SomeMethod(). This method needs to be called at the end of execute(). My question whether it is possible to call this without changing each and every derived class's execute() method?
public class Base {
public final void execute() {
doExecute();
someMethod();
}
protected abstract void doExecute();
public void someMethod() {
}
}
This solution prevents the super code smell.
Yes, but you have to change the callers then. Callers will have to call a doExecute() (find a better name for it though) method, which you define in your base class as final, and which calls execute(), then the common code.
Another option is aspect-oriented programming, but I wouldn't recommend it for this purpose, that is, to "hack" code.
The question is: why is changing the name of a method in a 100 or so classes such a problem? It's a click of the mouse with an IDE.
Not that I'm aware of. Next time you should consider that you might want to add some common action for all extended classes, and call for super.execute()!
Only by using something that instruments your code; this isn't possible with pure Java.
Let me state your problem as i understand : Animal class has Breath() method which has implementation and due to inheritance all the subclasses has this member and unless there is very different way of breathing nobody will override.
Now at the end of Breath method you want to call CloseEyes() method of animal class and may be that is true that some or all of the subclasses overrides CloseEyes() method.
So your problem : Everytime any animal breath you want to them to CloseEyes but from Animal class and not from the derived classes.
If there are already CloseEyes() methods in many derived classes then you are actually doing something wrong in calling base class's CloseEyes().
If you still want only base class's method to be called then why do you need same method name- you just say AnimalEyeClose() , make it private and have it in Animal class.
I have an abstract TemporalModel class (annotated with #MappedSuperclass) that adds created and updated fields to all extending models. I want to add a getLatest() static method to it:
public static TemporalModel getLatest() {
return find("order by created").first();
}
When I put this method on the base class, and call it through a concrete class (Transaction.getLatest()), I get an error:
UnsupportedOperationException occured : Please annotate your JPA model
with #javax.persistence.Entity annotation.
I suspect this is because JPA doesn't in fact know I'm calling this method "through" the base class (there is no real static method inheritance in Java).
Is there another way to implement this method once, instead of repeating it on all entity classes?
Update - one way to achieve this (which I'm using in another heavier app) is described here (gist). In my current app, however, I wouldn't like to use repositories, and I wondered if there's another, lighter solution.
Constructors and static methods can never be abstract. The idea behind an abstract class
is to create blueprints of methods, that have to get worked out in the subclass(es). I suggest trying an interface TemporalModel instead of an abstract class, in which you create the method public static TemporalModel getLatest();
I haven't used this Play framework, so I'm not sure about the details here, but usually, when one does the stuff you want to do, in Java, one simply specifies the concrete class as a parameter to the static method in question. It's kind of ugly, of course, but it is Java.
I assume that this find method is a static method that is added somehow (by annotation processing?) by this framework on every extending class, right? In that case, I think your only recourse is to do something like this:
public static <T extends TemporalModel> T getLatest(Class<T> cl) {
try {
/* I don't know what type the find() method returns, so you'll have to fix the casting */
return(cl.cast(cl.getMethod("find", String.class).invoke("order by created").first()));
} catch(AllThosePeskyReflectionExceptions e) {
throw(new Error(e));
}
}
I think that's the best way available given the premises. I know it's ugly, so I'd be happy to be wrong. :)
This might be simple for seasoned java developers but I just cant seem to figure it out. I read a post from here. The code was
View v = new View(this) {
#Override
protected void onDraw(Canvas canvas) {
System.out.println("large view on draw called");
super.onDraw(canvas);
}
};
It was an Android question. Here the user creates an instance of a view and overrides a method in a single line. Is there a name for this kind of coding?
My second doubt is, he overrides a protected method from another package. Isn't protected mean package private. I know this will work as I tried it out but I just couldn't figure out why it worked. So why is this code working?
I did try to google this and search in SO before asking but couldn't figure out an answer.
protected means (roughly) "available to sub-classes". (See this table.) Since the new View(this) { ... } creates a subclass, it is possible to override the method within it.
In this case it doesn't matter that you're in a different package. (See the protected line and second column in this table.) The fact that the method is in a subclass is sufficient to "get access" to a protected method.
Potential follow-up question: What sense does it make, if I can't call the method anyway?
All methods in Java are virtual. This means that whenever the View class performs a seemingly internal call to the onDraw method, this call will be dispatched to the overridden method.
That is not exactly a kind of coding. That is a Java anonymous class. It is very common in Android and in general with event listeners and that kind of stuff.
For more details you can read this link (probably not the best one):
The anonymous inner classes is very useful in some situation. For
example consider a situation where you need to create the instance of
an object without creating subclass of a class and also performing
additional tasks such as method overloading.
About your second question, the keyword protected means that the method is only available to subclasses, so it is possible to override the method.
This is an anonymous class. You are correct that you are overriding a protected method and this is perfectly normal. A protected method is visible, and can therefore be overridden, by a sub class, which is what you have created here.
Package protected is the default scope when you do not provide a scope for your variable or method. That is different to protected.
So many answeres were there for "protected", so i am going to other one :)
#override is informing the compiler to override the base class method, and if there is no base class method of this signature then throws compilation error.
These are called annotations. You can search for annotations topic in java. You can create custom annotations as well.
Regards,
SSuman185
Just like others here are already answered this is called anonymous class, and overriding protected methods is legal since protected methods are visible to child classes and classes in same package.