Is there any keyword or design pattern for doing this?
Please check the update
public abstract class Root
{
public abstract void foo();
}
public abstract class SubClass extends Root
{
public void foo()
{
// Do something
//---------------- Update -------------------//
// This method contains important code
// that is needed when I'm using a instance
// of SubClass and it is no instance of any
// other class extending SubClass
}
}
public class SubberClass extends SubClass
{
// Here is it not necessary to override foo()
// So is there a way to make this necessary?
// A way to obligate the developer make again the override
}
Thanks
If you are doing this, then you are probably abusing inheritance; inheritance, contrary to popular myth, is not intended for making custom hooks/handlers, but rather to enable alternative implementations.
If you want your user to provide some sort of function/hook/callback, then you should define an interface that provides just those methods that you need your user to define. Then you should require the user to pass in an instance of that interface to your object's constructor or passed into the function that needs it.
Aggregation, delegation, and composition are frequently better and safer design patterns than inheritance; forcing other users to inherit from your class, is incredibly risky, as it provides the user with many opportunities to violate the contract of your class or to invalidate the invariant of your base class.
If every class subclassing SubClass has to override foo() then why provide an implementation at all in SubClass? You can simply remove the method definition from SubClass and then all subclasses will be forced to provide an implementation.
If you really want to, you can re-declare foo as abstract.
public abstract class SubberClass extends SubClass
{
public abstract void foo();
}
Instead of overriding foo() in SubClass, create a new method fooImpl() and leave foo() abstract. This way, all classes must implement foo() but you can simply implement it by calling fooImpl() if that is already enough.
Yeah it is not necessary to override foo() in SubberClass.
You can't have it both ways. You can't provide a method with a default implementation AND require child classes override it. Instead of declaring the method as abstract in Root, you could define an interface (IFoo) with the method declared and then provide an abstract class that implements the interface. That would still require a concrete child class but would not require a method override.
Most of the time you see this type of pattern, an interface is used to define a set of methods and an abstract base class provides some default implementations for some but not all methods from the interface. This requires the concrete child class to provide code for the remaining methods and the option to override the default behaviors.
In any case, you can't provide a default behavior for a single method and require child classes to override that same method.
Related
I have an abstract class (showing only the relevant parts) with two overloaded methods.
abstract public class Component {
...
abstract protected void createPhysics();
abstract protected void createPhysics(Comp1D[] comp1DS);
...
}
In the subclasses which extend this abstract class I only want to use either the one with arguments or the one without, but never both of them. For example
public class Comp1D extends Component{
...
protected void createPhysics(Comp1D[] comp1Ds){
...
}
}
and
public class Comp3D extends Component{
...
protected void createPhysics(){
...
}
}
Of course this won't compile this way since the other createPhysics method is not implemented in the subclass. My quick and dirty solution would be to implement both methods in subclasses, but the unused method would have empty body.
Is there a more elegant way to solve it in Java 8?
With abstract methods, there is not. And on a syntactical level, it would not be sound either. If one has a Component, one can call both methods. How should one know which one is implemented and which one is not?
One could define both method in the abstract class and let them throw, for example, an UnsupportedOperationException, thus forcing sublcasses to override (at least one of) those methods if they wish to not throw such an exception. This, however, seems like a workaround for another problem.
I would suggest re-evaluating the overall architecture of that section and find another solution to the problem. For example, maybe two separated classes and handler for those classes would yield a cleaner architecture.
The question is, why do you want to use an Abstract class here. What if you plan to use an interface, with default implementations. You can implement the interface and override only the required method
The idea of using abstract class is when you want to define common method signatures in the class and force sub-classes to provide implementation for such methods. From this point of view the way you are trying to implement abstract class doesn't make much sense.
You can also use abstract class to define a base type to support O-O features like polymorphism and inheritance and i think this is what are you trying to do .
If this is the case i suggest to declare an abstract class without abstract methods or declare an interface with default implementation for both methods and then you can override in implementation classes.
As #Turning85 pointed out, such an implementation would not make much sense.
Either you want to give your successor classes the flexibility to implement both of the methods according to their own specific needs or you want to take this complexity away from them and implement the whole logic in the abstract class, where you could have something like this:
abstract class Component() {
protected void createDefaultPhysics() {
//implement
}
abstract protected void createPhysics(Comp1D[] comp1DS);
}
and your concrete classes:
public class Comp1D extends Component{
protected void createPhysics(Comp1D[] comp1Ds){
if(comp1Ds == null) {
createDefaultPhysics();
}
}
}
Let's say I have a class called GUIElement described by this code:
public abstract class GUIElement {
public abstract void onScroll();
//Other methods such as getX(), getY(), onClick() etc.
}
All GUI elements that extend this are obviously forced to write concrete code for onScroll provided they are a concrete class, but very few actually use this onScroll method as it is only handy in something like a long GUIText block.
My question is then, what is the best practice in this situation? Continue to force all child classes to write code even when mostly it will be empty, or make it concrete like so:
public abstract class GUIElement {
public void onScroll() {}
//Other methods such as getX(), getY(), onClick() etc.
}
and have the few classes that use it just override it.
Or maybe there are other, better alternatives?
If only a few classes need to implement the method, then the Adapter Pattern is a good choice. Which is, what your second approach basically is. Have an empty implementation in the parent class and only those child classes that need this functionality can override it, but they're not forced to do so.
Take a look at the MouseAdapter in the AWT package for instance. It implements the MouseListener interface, but leaves all methods empty. Child classes then can choose whether to override those methods or not.
Let's say I have a class called GUIElement described by this code:
public abstract class GUIElement {
public abstract void onScroll();
//Other methods such as getX(), getY(), onClick() etc.
}
All GUI elements that extend this are obviously forced to write concrete code for onScroll provided they are a concrete class, but very few actually use this onScroll method as it is only handy in something like a long GUIText block.
In an abstract class methods should be abstract because concrete methods in this abstract class use them, e.g.:
public abstract class GUIElement {
public void onScroll(){
// do stuff
SomeObject retunValue = calculateInSomeChiledClass();
// do other stuff
}
potected abstract SomeObject calculateInSomeChiledClass();
}
An abstract class should not have abstract methods for any other reason.
Make an empty concrete method is a way but it has a consequence as it doesn't force new declared class to override it.
If this consequence is not a drawback for you, using this way is fine.
Otherwise, if you want to be sure that subclasses specify explicitly how to implement the operation, you should keep the method as abstract and implement them when it is required and throwing UnsupportedOperationException or an empty implementation in the subclasses where the operation is not supported.
Both solutions are acceptable.
Follow the one or the second depends on the point that you want to stress on for your subclasses : simple API or explicit behavior to define.
i have an abstract class,this class is extended in her subclasses:
i implementend one method on this abstract class and i made the other method abstracts
the implemented method is a general method that every subclass object has to access on it.So i decided to implement it on the abstract class,avoid implementing the same method on each subclass.
little example:
public abstract class Foo{
//plus constructor and other stuff.
public abstract void differentTypeOfImplementation();
public void doSomething(Foo foo){
//do something with the generic Foo object passed
}
}
i want your opinion on this type of implementation,
regards.
This question is probably too open ended, but your solution is perfectly fine.
The alternative is that you can make an Interface with differentTypeOfImplementation(), and then a utility class with doSomething. That way, your subclasses can also extend from other classes. However, if subclasses may occasionally override doSomething, or if doSomething require accessing internal states of the object, then what you have is perfectly valid.
Implementing a method in an abstract class is very much valid and acceptable design. If this method implementation is necessary for all its subclasses then this is the way to go. In your example however - the signature of the method makes it little fishy - it looks like you are not using the super class state in any way . That means you could as well declare this method as static.
When inheriting from a base class in a scenario when not all methods will be implemented, is it better to put empty methods in the base class so that sub-classes that don't require that method can ignore it totally, while other classes must override the method if they want to implement it... e.g:
Base class:
public void myMethod() {
}
Sub-class that doesn't implement:
<nothing!>
Or is it better to leave the base class cleaner and just put an abstract method in and force the sub-class to flesh out a blank method if it doesn't implement that method?
Base class:
public abstract void myMethod();
Sub-class that doesn't implement:
public void myMethod() {
}
It's up to you and it really depends on the situation.
You can use abstract methods when you have an abstract class and you want classes which extend it to implement that method (because the abstract parent class uses the abstract method - it may be something like print()). It's similar to interface's methods but it's usually used in different scenarios. But I would use interface in most cases...
I would use abstract method only in case that myMethod() does a different thing in each class that extends the abstract parent... Otherwise, if myMethod() does usually the same thing and one or two classes need to override it, I will use the first solution.
Also look at the template method pattern. I don't know which case is yours so I can't answer this question in an exact way...
It is your design decision . If you want to force your developers to override myMethod and developed the logic. You should go for abstract class.
Both are not the most elegant solutions, though both can get the job done. Use the design pattern strategy design pattern http://www.newthinktank.com/2012/08/strategy-design-pattern-tutorial/
Coding style is up to you, depends on your requirement and everything has it own pros and cons.
In case of abstract class, it is not necessary to put only abstract method. I would recommend you, better to use Interface.
Whenever it is possible you should
Prefer interfaces to abstract classes
Because interfaces do not permit to contain method implementations, there is the
so called Abstract*Interface*, which is a combination of both technics:
In that case the Interface defines the type, while the abstract class provides a skeletal implementation.
An example are the Collection Framework which provides skeletal implemantations: AbstractCollection, AbstractList, AbstractSet and AbstractMap.
Further info see Josh Bloch, Effective Java 2nd Edition, Item 18
I think it comes down to whether there is a meaningful default implementation for myMethod(). If there is, put it in the base class and subclasses only override if they need something different.
If there is no meaningful default, and in practice every non-abstract subclass should either implement the method itself or inherit an implementation from an intermediate class, it is a very bad idea to provide a fake implementation in the base class. It converts an error the compiler could have detected to one that can only be found by testing.
One option to consider in some cases is providing a default implementation that throws UnsupportedOperationException.
The differenct in an abstract class is that you can but must not override that function.
So public void nothing() {} can be overridden and public abstract void nothing2(); must be overriden.
Are there some practical programming situations for someone to declare a class abstract when all the methods in it are concrete?
Well you could be using a template method pattern where there are multiple override points that all have default implementations but where the combined default implementations by themselves are not legal - any functional implementation must subclass.
(And yes, I dislike the template method pattern ;))
An abstract class is a class that is declared abstract - it may or may not include abstract methods. They cannot be instantiated so if you have an abstract class with concrete methods then it can be subclassed and the subclass can then be instantiated.
Immagine an interface whose declared methods usually show the same default behavior when implemented. When writing a class that needs to support the interface you have to define said default behavior over and over.
To facilitate implementation of your concrete classes you might want to provide an abstract class providing default behavior for each method. To support the interface in a concrete class you can derive from the abstract class and override methods if they deviate from the standard behavior. That way you'll avoid the repeated implementation of the same (redundant) default behavior.
Another possible use case is a decorator which delegates all calls to the wrapped instance. A concrete decorator implementation can override only those methods where functionality is added:
public interface Foo {
public void bar();
}
public abstract class FooDecorator implements Foo {
private final Foo wrapped;
public FooDecorator(Foo wrapped) { this.wrapped = wrapped; }
public void bar() { wrapped.bar(); }
}
public class TracingFoo extends FooDecorator {
//Omitting constructor code...
public void bar() {
log("Entering bar()");
super.bar();
log("Exiting bar()");
}
}
Although I don't really see the necessarity to declare FooDecorator as abstract (non-abstract example: HttpServletRequestWrapper).
Previous answers already hit the main issues, but there's a minor detail that might be worth mentioning.
You could have a factory that returns instances of (hidden) subclasses of the abstract class. The abstract class defines the contract on the resulting object, as well as providing default implementations, but the fact that the class is abstract both keeps it from being instantiated directly and also signals the fact that the identity of the "real" implementation class is not published.
Wondering why no one has pointed to the Practical Example of MouseAdapter:
http://docs.oracle.com/javase/6/docs/api/java/awt/event/MouseAdapter.html
An abstract adapter class for receiving mouse events. The methods in
this class are empty. This class exists as convenience for creating
listener objects.
Nice question :)
One thing is for sure ... this is certainly possible. The template suggestion by krosenvold is one good reason for doing this.
I just want to say that a class must not be declared abstract just for preventing it's instantiation.
This is referred in the Java Language Specification Section 8.1.1.1
When you have an important class but the system cannot create an instance fo this class, because
this class is parent of a lot of classes of the system;
this has a lot of responsability (methods used by a lot of class) for domain's requires;
this class not represents a concrete object;
Servlet Example:
All methods are concrete,
but the base class is useless by itself:
DeleteAuthor.java
Abstract class with concrete doGet method.
doGet calls file pointed to in protected string sql_path.
sql_path is null.
DeleteAuthorKeepBook.java
extends abstract class DeleteAuthor
sets sql_path to delete_author_KEEP_BOOK.sql
DeleteAuthorBurnBook.java
extends abstract class DeleteAuthor
sets sql_path to delete_author_BURN_BOOK.sql