I have event observers which all observe the same event, so I have an abstract superclass which observes that event and then the subclass overrides / implements the specific functionality.
The problem with this is that it doesn't observe the event unless I put the event observer method in the subclass (which defeats the purpose of my design).
I can most certainly do it this way, but I want to write as little code as possible.
Should it work this way (am I doing something else wrong)?
If it isn't supposed to work this way, then I can write a producer for one thing and then an interceptor. I thought that my first approach was simpler and more likely to be used properly by other developers.
example code:
SuperClass:
public abstract class AbstractFileWriter
{
public void onReady(#Observes ReadyEvent readyEvent)
{
try
{
handleReady(readyEvent, ...);
}
}
protected abstract handleReady(ReadyEvent readyEvent, otherParameters go here);
}
SubClass
public class XmlWriter extends AbstractFileWriter
{
protected handleReady( ... )
{ ... }
}
If I write it this way, handleReady is never invoked (and neither is onReady for that matter); however, if I write it with the observer method within the subclass, it works as expected. I want to write it this way as there is much less code I'd have to write and a little bit less abstraction which should make it easier to understand.
Walter
Either declare the relevant method in the superclass to be abstract or have it call an abstract "detail" method that each subclass implements.
I wrote a decorator as I mentioned above. This essentially does the same thing, just written slightly differently.
Walter
Related
I have been studying abstract methods lately and I can't understand why do we need them?
I mean, after all, we are just overriding them. Do you know its just a declaration? Why do we need them?
Also, I tried understanding this from the internet and everywhere there's an explanation like imagine there's an abstract class human then there're its subclasses disabled and not disabled then the abstract function in human class walking() will contain different body or code. Now what I am saying is why don't we just create a function in the disabled and not disabled subclasses instead of overriding. Thus again back to the question in the first paragraph. Please explain it.
One of the most obvious uses of abstract methods is letting the abstract class call them from an implementation of other methods.
Here is an example:
class AbstractToy {
protected abstract String getName();
protected abstract String getSize();
public String getDescription() {
return "This is a really "+getSize()+" "+getName();
}
}
class ToyBear extends AbstractToy {
protected override String getName() { return "bear"; }
protected override String getSize() { return "big"; }
}
class ToyPenguin extends AbstractToy {
protected override String getName() { return "penguin"; }
protected override String getSize() { return "tiny"; }
}
Note how AbstractToy's implementation of getDescription is able to call getName and getSize, even though the definitions are in the subclasses. This is an instance of a well-known design pattern called Template Method.
The abstract method definition in a base type is a contract that guarantees that every concrete implementation of that type will have an implementation of that method.
Without it, the compiler wouldn't allow you to call that method on a reference of the base-type, because it couldn't guarantee that such a method will always be there.
So if you have
MyBaseClass x = getAnInstance();
x.doTheThing();
and MyBaseClass doesn't have a doTheThing method, then the compiler will tell you that it can't let you do that. By adding an abstract doTheThing method you guarantee that every concrete implementation that getAnInstance() can return has an implementation, which is good enough for the compiler, so it'll let you call that method.
Basically a more fundamental truth, that needs to be groked first is this:
You will have instances where the type of the variable is more general than the type of the value it holds. In simple cases you can just make the variable be the specific type:
MyDerivedClassA a = new MyDerivcedClassA();
In that case you could obviously call any method of MyDerivedClassA and wouldn't need any abstract methods in the base class.
But sometimes you want to do a thing with any MyBaseClass instance and you don't know what specific type it is:
public void doTheThingsForAll(Collection<? extends MyBaseClass> baseClassReferences) {
for (MyBaseClass myBaseReference : baseClassReferences) {
myBaseReference.doTheThing();
}
}
If your MyBaseClass didn't have the doTheThing abstract method, then the compiler wouldn't let you do that.
To continue with your example, at some point you might have a List of humans, and you don't really care whether they are disabled or not, all you care about is that you want to call the walking() method on them. In order to do that, the Human class needs to define a walking() method. However, you might not know how to implement that without knowing whether the human is or isn't disabled. So you leave the implementation to the inheriting classes.
There are some examples of how you'd use this in the other answers, so let me give some explanation of why you might do this.
First, one common rule of Object Oriented Design is that you should, in general, try to program to interfaces rather than specific implementations. This tends to improve the program's flexibility and maintainability if you need to change some behavior later. For example, in one program I wrote, we were writing data to CSV files. We later decided to switch to writing to Excel files instead. Programming to interfaces (rather than a specific implementation) made it a lot easier for us to make this change because we could just "drop in" a new class to write to Excel files in place of the class to write to CSV files.
You probably haven't studied this yet, but this is actually important for certain design patterns. A few notable examples of where this is potentially helpful are the Factory Pattern, the Strategy Pattern, and the State Pattern.
For context, a Design Pattern is a standard way of describing and documenting a solution to a known problem. If, for example, someone says "you should use the strategy pattern to solve this problem," this makes the general idea of how you should approach the problem clear.
Because sometimes we need a method that should behave differently in its instances.
For example, imagine a class Animal which contains a method Shout.
We are going to have different instances of this Animal class but we need to implement the method differently in some cases like below:
class Animal:
/**
different properties and methods
which are shared between all animals here
*/
...
method shout():
pass
class Dog extends Animal:
method shout():
makeDogVoice()
class Cat extends Animal:
method shout():
makeCatVoice()
dog = new Animal
cat = new Animal
dog.shout()
cat.shout()
So dog shouts like dogs, and cat shouts like cats! Without implementing the shared behaviors twice
There is a different behavior of shouting in these instances. So we need abstract classes.
Suppose you don't know about implementation and still want to declare a method then we can do that with the help of abstract modifier and making it an abstract method. For abstract method only declaration is available but not the implementation. Hence they should end with ;
Example:
public abstract void m1(); // this is correct
public abstract void m1(){ ... } // this is wrong
Advantage: By declaring abstract method in parent class we can provide guideline to child classes such that which methods are compulsory to implement.
Example:
abstract class Vehicle{
abstract int getNoOfWheels();
}
Class Bus extends Car{
public int getNoOfWheels(){
return 4;
}
}
If you want the short answer, think of this:
You have an abstract class Car.
You implement 2 classes that extend it, Ferrari and Mercedes.
Now:
What if you did one of the following, for the method drive(), common to all cars:
1) changed the visibility of the method,
2) changed the name of the method from driving to Driving,
3) changed the return type, from a boolean to an int
Think about it. It might not seem to make any difference right, because they are different implementations?
Wrong!
If I am iterating through an array of cars, I would have to call a different method for each type of car, thereby making this implementation of abstract useless.
Abstract classes are there to group classes with a common template, that share common properties. One way this helps would be the looping over the array:
Abstract methods ensure that all cars declare the same method,
and therefore, any object of a subclass of Car will have the method drive(), as defined in the abstract class, making the for loop mentioned easy to implement.
Hope this helps.
I'm not quite sure how to word this question, but hopefully the example will make it a bit more clear. I'm trying to figure out the best way to have one of the implemented abstract methods not be called (do nothing) and I'm curious if my current approach is at all somewhat right.
abstract class Vehicle {
void doSomething() {
if (this.getClass() instanceof Chevy) {
operateOnCar();
}
}
abstract void operateOnCar();
}
class Chevy extends Vehicle {
#Override
void operateOnCar() {
print("Doing something to a car")
}
}
class HarleyDavidson extends Vehicle {
#Override
void operateOnCar() {
throw Exception("This isn't a car")
}
}
The other approach I can think of is to have the HarleyDavidson class implement operateOnCar()but do absolutely nothing - i.e. an empty method body. Is that potentially better? Maybe neither of these are viable examples and I should reconsider my design. Thanks!
Edit: tried to make my example a bit more clear
I'm trying to figure out the best way to have one of the implemented
abstract methods not be called (do nothing)
Asserting that a method should not be called is totally different from asserting that it should do nothing. It is furthermore wrongheaded to define a method on the superclass, regardless of abstractness, that is not ok to call on any instance of any subclass. Thus, some variation on the "do nothing" alternative is a much better choice.
And what's so hard about a method doing nothing when it does not need even to provide a return value? This is a method that does nothing:
void isCar() {
// empty
}
I should also observe at this point a method named isCar would be expected by most Java programmers to return a boolean indicating whether the object on which it is invoked is a "car", whatever that means in context. It would come as a surprise that such a method is declared not to return anything, and perhaps an even bigger surprise that it writes to System.out.
You're blurring the responsibilities of your abstract class and its concrete implementations. This is evidenced by your doSomething method.
void doSomething() {
if (this.getClass() instanceof Chevy) {
operateOnCar();
}
}
Your abstract class shouldn't care what instance it is; only the Chevy class needs to do something with this.
This may be why you're getting mixed up with the operateOnCar method. A Car is a Vehicle, but not all Vehicles are Cars. You could have trucks, vans, locomotives, boats, planes...all of which are vehicles in their own right, but definitely wouldn't support an operateOnCar method.
It may be as simple as renaming your method. You can definitely operate or fix a vehicle. You just want to keep that as agnostic as possible at the higher levels of the inheritance chain.
If you make a class, than that class (including its derived classes) should only have properties/methods related to that class. If a property/method does not fit, it shouldn't be in a class.
So how you can put OperateOnCar somewhere: with the strategy pattern, which is a common design pattern.
Than you make an interface OperatableOnVehicle, with an operation OperateOnVehicle. For vehicle it will be implemented, for a HarleyDavidson it is not implemented.
Try to avoid to use the word 'car'.
There are many examples to be found on internet about the strategy pattern, so google for more information about it's background.
I think if object calling this method throws the following exception:
throw Exception("This method should only be called if the car is a chevy")
There would be better to print out that it's not a car. As the name of the method suggests, it should return boolean
Is Chevy a car? Yes it is - return true and inform about the result
Is HarleyDavidson a car? No, it is not - return false and inform as well
is for exampleBicycle a car? No, definitely not. Is it a vehicle? Yes. Is legitime to ask it whether it's a car? Why not?
By the way, have you considered the following hierarchy?
Vehicle <- Car <- Chevy
Vehicle <- (Motocycle ) <- HarleyDavidson
I have two classes. Let's call them PostClass and CommentClass. Both classes implement the Reportable interface:
public interface Reportable {
void report();
boolean isReported();
. . .
Now I need to add two additional methods to each one of the classes. These methods logically fit into the same interface but needs to have different names. For example:
PostClass will have methods -> remove(), restore()
CommentClass will have methods -> hide(), show()
Question: What would be the preferred way to design this change? The options are as I see it:
Create an additional interface which will extend the Reportable interface. Problem: Too many interfaces
Add all four new methods into the Reportable interface and then just leave the irrelevant two methods unimplemented in each class. Problem: Untidy/ugly
Don't worry about having a few more interfaces, as long as their use and purpose is clear. These 2 options are valid:
PostClass implements RemovableReportable, which extends Reportable; And
CommentClass implements HideableReportable, which extends Reportable.
PostClass implements both Reportable and Removable; And
CommentClass implements both Reportable and Hideable.
But adding all four new methods into the Reportable interface and leaving two methods unimplemented in each class is very wrong, since it does not lead to code which is clean and easy to understand and use. The developer would have to learn which method to use in each case, thus making your code more difficult to use and modify. And what happens if some developer calls the wrong method? If the wrong method does nothing, bugs may go unnoticed. If it throws an exception, this will only catch bugs at runtime. And if it calls the other method then you have two ways of doing the same thing, which is also bad and confusing.
Unused methods in an interface are a code smell, and may indicate a design flaw.
If they do the same thing, then make up names that encompass the function; although that doesn't sound like what you want given the existing names.
Option 3: Create two new interfaces, Removable and Hideable and have each class implement the appropriate interface(s).
On second thought, I would probably recommend using hide() and show() since that seems to capture what's happening best.
While the question would likely be classified as opinion based, my approach would be to still add two methods (show(),hide()) to the interface and have the classes implement it.
Below are few other options :
If you are using JDK8 you can try adding the above two methods as default-methods in the interface so that it does not immediately break the existing implementation.
Also, apparently its possible to invoke the abstract method from a default method in the interface so it would technically be possible to have two generically named abstract methods and two (or four more) that are specifically named default methods but that would be overkill and would only add to the confusion.
You could consider having a total of six new methods. show and hide being abstract and also showPost/hidePost and showComment and hideComment being default classes which in turn invoke the abstract show and hide respectively. That way even if some implementation class calls the wrong alias by mistake it would still invoke the correct implementation (in theory).
Whatever I am going to describe in this answer is purely my opinion and subjective.
The following points must be kept in mind when designing this:
Any method added to Reportable (or in general any supertype) should be applicable to all subtypes regardless.
A method should describe a behaviour of the class, something that the class is capable of 'doing'.
Point 2 explanation
Think of the method postClass.remove(), which can be read as 'A PostClass knows how to remove...'. But remove what? Itself? From where?
For me, 'removing' and 'restoring/adding' seems like something that can be done on a Collection of PostClass or CommentClass by and not something that these classes do themselves. If I guess correctly, this is indeed how you must be using PostClass and CommentClass in your application (i.e. as a Collection of some sort). Now, a PostClass or CommentClass can get a callback onRemove(), onRestore(), onHide() or onShow() to do what's necessary for each of this actions when being removed/restored/hidden/shown.
The advantage of callbacks is that a class can choose to call super if they don't intend to do something special during the action.
Design 1 - Reportable has the behaviour of being hidden,shown,restored and removed
So, for all 'reports' of your application, you can add these callbacks to the Reportable interface itself.
public interface Reportable {
void report();
boolean isReported();
void onRestore();
void onRemove();
void onHide();
void onShow();
}
Usage could be something like this
public class User {
private List<Reportable> reports;
//... more User related code
public void deleteReport(Reportable report) {
//give report a chance to cleanup
report.onDelete();
//delete from user's list of reports
this.reports.remove(report);
//more code
}
Design 2 - Having separate interfaces
public interface Viewable {
void onHide();
void onShow();
}
public interface Disposable {
void onRemove();
void onRestore();
}
public class PostClass implements Reportable, Disposable {
}
public class CommentClass implements Reportable, Viewable {
}
Usage for this is pretty self explanatory I guess.
I prefer Design 2 as it seems more clean and adheres to 'SOLID' design principles.
Hope this helps.
In .NET, one can specify a "mustoverride" attribute to a method in a particular superclass to ensure that subclasses override that particular method.
I was wondering whether anybody has a custom java annotation that could achieve the same effect. Essentially what i want is to push for subclasses to override a method in a superclass that itself has some logic that must be run-through. I dont want to use abstract methods or interfaces, because i want some common functionality to be run in the super method, but more-or-less produce a compiler warning/error denoting that derivative classes should override a given method.
I don't quite see why you would not want to use abstract modifier -- this is intended for forcing implementation by sub-class, and only need to be used for some methods, not all. Or maybe you are thinking of C++ style "pure abstract" classes?
But one other thing that many Java developers are not aware of is that it is also possible to override non-abstract methods and declare them abstract; like:
public abstract String toString(); // force re-definition
so that even though java.lang.Object already defines an implementation, you can force sub-classes to define it again.
Ignoring abstract methods, there is no such facility in Java. Perhaps its possible to create a compile-time annotation to force that behaviour (and I'm not convinced it is) but that's it.
The real kicker is "override a method in a superclass that itself has some logic that must be run through". If you override a method, the superclass's method won't be called unless you explicitly call it.
In these sort of situations I've tended to do something like:
abstract public class Worker implements Runnable {
#Override
public final void run() {
beforeWork();
doWork();
afterWork();
}
protected void beforeWork() { }
protected void afterWork() { }
abstract protected void doWork();
}
to force a particular logic structure over an interface's method. You could use this, for example, to count invocations without having to worry about whether the user calls super.run(), etc.
... and if declaring a base class abstract is not an option you can always throw an UnsupportedOperationException
class BaseClass {
void mustOverride() {
throw new UnsupportedOperationException("Must implement");
}
}
But this is not a compile-time check of course...
I'm not sure which attribute you're thinking about in .NET.
In VB you can apply the MustOverride modifier to a method, but that's just the equivalent to making the method abstract in Java. You don't need an attribute/annotation, as the concept is built into the languages. It's more than just applying metadata - there's also the crucial difference that an abstract method doesn't include any implementation itself.
If you do think there's such an attribute, please could you say which one you mean?
Android has a new annotation out as announced in the Google I/O 2015:
#callSuper
More details here:
http://tools.android.com/tech-docs/support-annotations
If you need some default behaviour, but for some reason it should not be used by specializations, like a implementation of a logic in a non abstract Adapter class just for easy of prototyping but which should not be used in production for instance, you could encapsulate that logic and log a warning that it is being used, without actually having to run it.
The base class constructor could check if the variable holding the logic points to the default one. (writing in very abstract terms as I think it should work on any language)
It would be something like this (uncompiled, untested and incomplete) Java (up to 7) example:
public interface SomeLogic {
void execute();
}
public class BaseClass {
//...private stuff and the logging framework of your preference...
private static final SomeLogic MUST_OVERRIDE = new SomeLogic() {
public void execute() {
//do some default naive stuff
}
};
protected SomeLogic getLogic() { return MUST_OVERRIDE; }
//the method that probably would be marked as MustOverride if the option existed in the language, maybe with another name as this exists in VB but with the same objective as the abstract keyword in Java
public void executeLogic() {
getLogic().execute();
}
public BaseClass() {
if (getLogic() == MUST_OVERRIDE) {
log.warn("Using default logic for the important SomeLogic.execute method, but it is not intended for production. Please override the getLogic to return a proper implementation ASAP");
}
}
}
public GoodSpecialization extends BaseClass {
public SomeLogic getLogic() {
//returns a proper implementation to do whatever was specified for the execute method
}
//do some other specialized stuff...
}
public BadSpecialization extends BaseClass {
//do lots of specialized stuff but doesn't override getLogic...
}
Some things could be different depending on the requirements, and clearly simpler, especially for languages with lambda expressions, but the basic idea would be the same.
Without the thing built in, there is always some way to emulate it, in this example you would get a runtime warning in a log file with a home-made-pattern-like-solution, that only your needs should point if it is enough or a more hardcore bytecode manipulation, ide plugin development or whatever wizardry is needed.
I've been thinking about this.
While I don't know of any way to require it with a compile error, you might try writing a custom PMD rule to raise a red-flag if your forgot to override.
There are already loads of PMD rules that do things like reminding you to implement HhashCode if you choose to override equals. Perhaps something could be done like that.
I've never done this before, so I'm not the one to write a tutorial, but a good place to start would be this link http://techtraits.com/programming/2011/11/05/custom-pmd-rules-using-xpath/ In this example, he basically creates a little warning if you decide to use a wildcard in an import package. Use it as a starting point to explore how PMD can analyze your source code, visit each member of a hierarchy, and identify where you forgot to implement a specific method.
Annotations are also a possibility, but you'd have to figure out your own way to implement the navigation through the class path. I believe PMD already handles this. Additionally, PMD has some really good integration with IDEs.
https://pmd.github.io/
Referring here
A is a precompiled Java class (I also have the source file)
B is a Java class that I am authoring
B extends A.
How can logic be implemented such that A can call the methods that B has.
The following are the conditions:
I don't want to touch A(only as a
last option though that is if no
other solution exists).
I don't want to use reflection.
As stated, if needed I could modify A.
What could be the possible solution either way?
Class A should define the methods it's going to call (probably as abstract ones, and A should be an abstract class, per Paul Haahr's excellent guide); B can (in fact to be concrete MUST, if the method are abstract) override those methods. Now, calls to those methods from other methods in A, when happening in an instance of class B, go to B's overrides.
The overall design pattern is known as Template Method; the methods to be overridden are often called "hook methods", and the method performing the calls, the "organizing method".
Yes it seems that if you override the super/base-classes's functions, calls to those functions in the base class will go to the child/derived class. Seems like a bad design in my opinion, but there you go.
class Base
{
public void foo()
{
doStuff();
}
public void doStuff()
{
print("base");
}
}
class Derived extends Base
{
#Override
public void doStuff()
{
print("derived");
}
}
new Derived().foo(); // Prints "derived".
Obviously all of Derived's methods have to be already defined in Base, but to do it otherwise (without introspection) would be logically impossible.
I would be rather hesitant to do this. Please correct me if I am wrong and then I will delete, but it sounds like you want to maintain an A object along with a B object. If they indeed are not the same object, the "tying together" (that's a scientific term) you'll have to do would be pretty ugly.