Reputation: 406
I have a question regarding the structures of my classes in java :
I have a first class : MyClass that is abstract
public abstract class MyClass
{
protected void abstract monitor();
}
then I have an abstract iterator on it
public abstract class MyClassIterator<T> extends MyClass
{
protected void abstract monitor(T data);
}
In practice I will after create classes that will either inherit from MyClass or MyClassIterator.
I want to make sure all instances of MyClass implement monitor but for the iterator ones, how can I avoid inserting something like
protected void monitor() {};
just to implement it :/
Thanks for any idea :)
Upvotes: 1
Views: 2582
Reputation: 1206
If you don't want that MyClassIterator
subclasses will have to implement this method, then you have to add the empty implementation to MyClassIterator
.
You can also throw some exception in the implementation.
public abstract class MyClassIterator<T> extends MyClass
{
protected abstract void monitor(T data);
protected void monitor() {
//optional
throw new UnsupportedOperationException();
}
}
Note: You can't write void
before abstract
, you need to fix this in your monitor(T data)
method, like in my answer.
Upvotes: 1
Reputation: 16833
Add a default implementation of monitor
in MyClass
, with a customized exception
public abstract class MyClass
{
protected void abstract monitor()
{
throw new NotImplementedException();
}
}
Thereby, MyClassIterator
won't have to implement the method and other subclasses of MyClass
will have to override it.
Upvotes: 3