Just a simple syntax question. Suppose we have an interface which we will call IMyClass, and an abstract class that implements which we will call AbstractMyClass and is declared as follows:
public abstract class AbstractMyClass implements IMyClass {
}
Now when we create a concrete implementation of MyClass which we will call... MyClass!, there are two ways in which we can declare it:
public class MyClass extends AbstractMyClass {
}
and
public class MyClass extends AbstractMyClass implements IMyClass {
}
What's best here? I'm supposing the answer to this is just a matter of preference but just wanted to hear some thoughts on this.
Thanks in advance,
Joseph.
The latter form is more explicit about the fact that MyClass is implementing IMyClass intentionally and not by accident. If that's what you intend to stress, this form is more clear. It also guards against future changes to AbstractMyClass. Perhaps at some point it ceases to implement IMyClass.
In most cases the first form is sufficient and extra verbosity buys you nothing.
It is just a matter of preference. FWIW, you can find examples for both in the JDK source:
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
public class ThreadPoolExecutor extends AbstractExecutorService
Related
I am writing some classes using Generics but I can't find a solution
for the class SolutionsSubset and so I a getting the error
"type parameter S is not within its bound". I have read previous
questions about the same error but I can't solve it for my case.
Could anybody help me to improve my knowledge about generics? Any
reference to a good book (I can find in google a lot of information
but if someone can reccommend a book, tutorial, etc. will be welcome).
Although I tried to keep in mind the rules to ask a question but I
apologize if my question doesn't fulfill these rules.
I have the following classes and interfaces:
public interface Subset<T extends Comparable<T>> extends Comparable<Subset<T>>
public class MathSubset<T extends Comparable<T>> extends TreeSet<T> implements Subset<T>
public interface Solution<T extends Comparable<T>>
public interface Solutions<S extends Solution<?>> extends Iterable<S>
public class SolutionsSubset<S extends Solution<?>> extends MathSubset<S> implements Solutions<S>
I need that Subset extends Comparable. In SolutionsSubset, the class MathSubset stores Solution objects. How do I have to change these definition to make it work?
Thanks you in advance
In order to be used as the type argument in MathSubset, SolutionsSubsets S must extend Comparable<S>. As a compilable example:
import java.util.TreeSet;
interface Subset<T extends Comparable<T>>
extends Comparable<Subset<T>> { }
class MathSubset<T extends Comparable<T>>
extends TreeSet<T>
implements Subset<T>
{
public int compareTo(Subset<T> other) { throw new Error(); }
}
interface Solution<T extends Comparable<T>> { }
interface Solutions<S extends Solution<?>> extends Iterable<S> { }
class SolutionsSubset<S extends Solution<?> & Comparable<S>>
extends MathSubset<S>
implements Solutions<S>
{ }
A few comments: This is very abstract example, and so not easy to think about. Laying out the code so you don't need to scroll is good. There's an awful lot of inheritance going on here, perhaps compose rather than, say, extending TreeSet. It's difficult to distinguish between the identifiers Solutions and Solution.
Generics are something that can quickly get out of hand, especially if you try to "be all generic" all at once. Less is more. What always helps me is to start concrete (including the implementation) and then slowly substitute generic parameters in, one parameter and class at a time.
Could anybody help me to improve my knowledge about generics?
http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
Not a tutorial, but lots of useful info. Its one of those references that you read the parts you can understand, but come back to over and over again in the future as you gain more mastery and more of it begins to make sense.
First of all, here is the full error (which is specific to MathSubset not getting a proper parameter): Bound mismatch: The type S is not a valid substitute for the bounded parameter <T extends Comparable<T>> of the type QifFixer.MathSubset<T>
The problem is that MathSubset expects a <T extends Comparable<T>, but you're giving it a S extends Solution<?> - those types having nothing to do with each other, because a Solution does not inherit or implement Comparable<T>.
If anything, you could try this:
public class SolutionsSubset<S extends Comparable<S>> extends
MathSubset<S> implements Solutions<Solution<S>>;
Unfortunately, this will STILL not work because MathSubset implements Iterable, but so does Solutions.
An easy fix would be for Solutions to not extend Iterable, but it really sounds to me like you're trying to use a more complex approach than you need to. May be a "has-a" instead of "is-a" design might be more beneficial here?
I want to know that is there any use of empty abstract class in Java? If so, what is it?
An empty abstract class is very much equivalent to an interface except that it can extend a class
abstract class myAbstractClass // extends anotherClass implements anInterface
{
}
interface myInterface // extends anotherInterface
{
}
This pattern is called Marker interface and SO has a lot of good data about it already: What is the purpose of a marker interface?
you can only inherit from one abstract class. Then this is useful to avoid inheritance.
Yes, sometimes you need a base class for implement polymorphism.
I'd like to implement the following classes with the following hierarchy:
public class DwellingPropertySetter
extends AbstractPropertySetter<Dwelling>
public class HousePropertySetter
extends DwellingPropertySetter<House>
public class SkyscrapperPropertySetter
extends HousePropertySetter<Skyscrapper>
Unfortunately this code won't compile. A way to do it would be this:
public class DwellingPropertySetter<T extends Dwelling>
extends AbstractPropertySetter<T>
public class HousePropertySetter<T extends House>
extends DwellingPropertySetter<T>
public class SkyscrapperPropertySetter<T extends Skyscrapper>
extends HousePropertySetter<T>
But for me those extends keywords are unnecessary.
Whenever I want to use a SkyscrapperPropertySetter I'd have to specify a type parameter. This is useless and would then look like SkyscrapperPropertySetter<Skyscraper>.
Do you know a way out for me? The only other way I know to realise my first hierarchy would be using interfaces and delegate methods.
I think you have correctly recognized it is pointless to have something like ChickenArrayList<Chicken>, so you can either create something like
class ChickenArrayList extends ArrayList<Chicken>
OR, if you want to reuse some functionality in ChickenArrayList, you may have to make it abstract (and generic) and put another concrete, non-generic class on top of it:
class AbsChickenArrayList<T extends Chicken> extends ArrayList<T>
// and
class ChickenArrayList extends AbsChickenArrayList<Chicken>
class HenArrayList extends AbsChickenArrayList<Hen>
I know this is quite verbose, but this is the best you can do with this ~18 year old language.
I think you can achieve what is reasonable. If you have
public class DwellingPropertySetter
extends AbstractPropertySetter<Dwelling>
That means you have already made DwellingPropertySetter non-generic, all the method signatures will use Dwelling. If you say
public class DwellingPropertySetter<T extends Dwelling>
extends AbstractPropertySetter<T>
that means there can be various DwellingPropertySetters -- and you really would like to have different ones, so I think this is what you really want to keep. Or is it your complaint that you want both a DwellingPropertySetter with no args, where Dwelling is assumed, AND a subclass extending DwellingPropertySetter<T> with a different T? That cannot be had with Java Generics.
I'm programming with java.
Let's say I have an "MyInterface" interface, and a "MyClass" abstract class.
I want to ensure that every class implementing the "MyInterface" interface is inherited from "MyClass".
An inherited class from MyClass is perfectly able to NOT implement the "MyInterface" interface.
Is this possible ? Thanks.
I'm sorry if my english is bad but I'm french.
I want to ensure that every class
implementing the "MyInterface"
interface is inherited from "MyClass".
Nope. That's not possible. The whole point of an interface is to make it so that classes from different inheritance hierarchies can implement support for a pre-defined set of capabilities.
AFAIK, you can't do this directly.
Generics let you say something like this, if it helps:
public <T extends MyClass & MyInterface> void foo(T param) { /**/ }
So, you can only call foo() with parameters that are both MyClass and MyInterface.
Or, why not have two abstract base classes?
abstract class MyClass { /* stuff here */ }
abstract class MyInterfaceClass extends MyClass { /* empty */ }
Then, use MyInterfaceClass instead of MyInterface.
Or, if you just care about containers, write your own:
static class MyList extends ArrayList<MyInterface> {
#Deprecated
public boolean add(MyInterface obj) {
assert obj instanceof MyClass;
return super.add(obj);
}
public <T extends MyClass & MyInterface> boolean add(T obj) {
return super.add(obj);
}
}
Then, you will get a deprecation warning any time you make a mistake.
But my question remains - what problem are you trying to solve? Can you use more descriptive names instead of "Class" and "Interface"? Perhaps the right solution is something completely different..
No, it is not possible. Any class can implement MyInterface. There is no way to limit implementors to subclasses of MyClass.
If you really need a limitation like that I think you'll be stuck with having to not use an interface and instead use MyClass in place of an interface.
I'm really confused, and I've read a TON of questions on this topic and I have not been able to pinpoint anything specifically that an interface can do that an abstract class cannot do.
Is there anything an interface can do that an abstract class cannot do?
I am asking in the context of my Java class, but feel free to remove the java tag if it applies to other languages as well (possibly C#?).
Edit: I understand that an abstract class can do things an interface cannot, but if an abstract class can do everything an interface can do, then what is the point of an interface? What does "implement multiple interfaces" mean?
Interfaces as such cannot do what abstract classes do.
This is because abstract classes can contain code - interfaces cannot. But any given class can only have one superclass - extends - as opposed to any number of interfaces - implements, so if you use abstract classes you essentially paint yourself in a corner of the inheritance tree, because your class can only extend a single class.
This limitation does not apply to interfaces, allowing a single class to have many purposes depending on how many interfaces it implements.
You can't inherit from multiple abstract classes in c#, but you can implement multiple interfaces.
I think this may apply to java too
Edit:
You can't inherit from multiple classes. If you have an abstract class called Clonable, and an abstract class called Disposable then you can only inherit one of these classes and you're forced to make a decision about which class your class should be a subtype of:
e.g:
public abstract class Clonable
{
public abstract void Clone();
}
public abstract class Disposable
{
public abstract void Dispose();
}
// MyClass cannot be Disposable too, it is not allowed by the language
public class MyClass : Clonable
{
override void Clone()
{
}
}
Note it is a design decision of the language to allow you only to inherit from one class.
If on the other hand you have interfaces, the language allows you to implement both
e.g.
public interface IClonable
{
void Clone();
}
public interface IDisposable
{
void Dispose();
}
public class MyClass : IClonable, IDisposable
{
void IClonable.Clone()
{
}
void IDisposable.Dispose()
{
}
}
Well read:
http://mindprod.com/jgloss/interface.html
http://mindprod.com/jgloss/interfacevsabstract.html
What does "implement multiple interfaces" mean?
Consider:
public static interface Ifun extends Comparable<Ifun>, Serializable {}//or
public static class Cfun2 implements Comparable<Cfun>, Serializable
When class implements Ifun, then:
Comparable interface imposes a total ordering on the objects of each class that implements it. Objects that implement this interface can be sorted automatically by Collections.sort.
The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
It means object can have more then 1 interface.
Interfaces are non instantiable classes that only contains methods that subclasses can inherit. The only thing that interfaces can do (in java) is that a class can implement many interfaces while a class can only extend 1 abstract class.