I am going over some code and I am adding some interfaces so i can make sure all the classes follow the same basic guidelines.
Now I have an interface called Uni < T > which takes exactly one generic argument.
Say I have a class which implements Uni< Foo > then I would like that class to have this method public foo getFoo(){};
Is there any way to add this method to the interface? I would prefer if i could do something like this in my interface public T getT(); and the second T gets replaced by the generic argument.
I can't just call it "get" because I would like some classes to implement multiple versions of Uni. public Example implements Uni<Foo1>,Uni<Foo2>
I know I can give the function 'get' an argument Foo or Class but I'd rather not so I thought I'd ask here.
(I would also mess up the naming convection if i did this)
No, not possible. And as generics in Java are implemented via erasure (i.e. dropped by the compiler), you will also not be able to implement multiple versions in a single class.
its not possible with java but you can do it like this
public interface example<T> {
public void yourmethod(T object);
}
make the interface according to the generic type you want.
Related
This is a tricky one - I have a java interface that I want to implement in scala:
public interface Foo {
public void bar(scala.Array arr);
}
Is it even possible to implement in scala? when I try:
class FooImpl extends Foo {
override def bar(arr: Array[_]): Unit = ???
}
I get:
Error:(13, 7) class FooImpl needs to be abstract, since method bar
in trait Foo of type (x$1: Array)Unit is not defined
(Note that Array does not match Array[_]. To implement a raw type, use
Array[_])
class FooImpl extends Foo {
The error message is giving you the answer for any generic type other than Array (after replacing the name, of course):
To implement a raw type, use Array[_]
"Raw type" is what Java calls a generic type used without a type parameter and e.g. https://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html explains why you should not use them except to interface with now horribly obsolete pre-Java-5 code. So if it is at all an option, you should fix the Java interface in the first place.
Now, why does this not work for Array? It's a special type, which is really built into compiler. Its instances are real JVM arrays, which don't have a common type in Java. So when it's used in Scala code, the compiled bytecode doesn't use scala.Array at all. I guess that it only exists as a JVM type (unlike e.g. scala.Any or scala.Null) to put the static methods there, but all instance methods are defined as throw new Error(). It seems the error message didn't take this unique case into account.
So, the answer is: no, it can't be implemented in Scala, as far as I am aware. But it can't be non-trivially implemented in Java either. And even for trivial implementations, you'd run into the same issues when trying to write code using it.
To make the code work you either have to
Make the FooImpl declaration as abstract class
Implement the bar method
because "Java interfaces don’t implement behaviour".
For your reference see this page.
First I want to clarify that I don't have any real business requirements for that, It's a purely theoretical question.
Assuming that we have these two Interfaces :
public interface SuperInterface {
void doSuperStaff();
void doComStaff();
}
public interface SubInterface extends SuperInterface {
// Something here to invalidate doSuperStaff()
}
Is there any way to invalidate / disable the doSuperStaff() for all classes that implement the SubInterface? So only the classes that directly implement SuperInterface can use that method and override it.
NB: I know that we can resolve that in a conceptual manner, but I want to know if there is a way to make that possible technically: using annotations for example ( like the #Deprectaed, which only instructs the compiler that the method is deprecated.)....
Limited, but the following helps a bit.
public interface SubInterface extends SuperInterface {
#Deprecated
void doSuperStaff();
}
Or even
public interface SubInterface extends SuperInterface {
#Deprecated
default void doSuperStaff() {
throw new UnsupportedOperationException("...");
}
}
UPDATE If it's purely theoritical and you are not stuck with a legacy design you can't change, then it's bad idea to try and remove Super interface methods on a sub-interface (or class). It's indicative the design is wrong (Dog -> Animal (useLegs, hasBody), Owl -> Animal (useLegs-??, hasBody). useLegs in this case doesn't belong in Animal.
But if you have legacy code you want to remove it from, and enforce it with Compile-time errors, this approach will work.
You can remove the method with Aspects. Create a pointcut that triggers when the method is called, add Around Advice which is triggered on that pointcut and throws an unsupported operation exception rather than proceed.
With AspectJ Spring syntax it looks something like this (Syntax details here -http://www.eclipse.org/aspectj/doc/next/adk15notebook/ataspectj-pcadvice.html)
#Around("call(* SubInterface.doSuperStuff())")
public Object removeMethod(ProceedingJoinPoint thisJoinPoint) {
throw new UnsupportedOperationException("...");
}
You can also use the native AspectJ language and it's Eclipse plugin to have Eclipse (or your build) show a compile error on the call site if any code attempts to use it. I think that would look something like this (https://eclipse.org/aspectj/doc/released/adk15notebook/annotations-decp.html)
declare error : call(* SubInterface.doSuperStuff())
: "Method doSuperStuff removed from SubInterface";
As you said the answer is NO.
This is simple illustration, why this feature cannot be added.
Firstly the meaning of Interface in Java is Behavior
Suppose if I create a new interface AdavancedComparable<T> which extends java.lang.Comparable<T> and if I deprecate the public int compareTo(T o); in my AdvancedComparable interface and add my own method like advancedCompare(T o);
public interface AdavancedComparable<T> extends Comparable<T> {
// invalidate/deprecate for compareTo method using requested feature somehow
public int advancedCompare(T o);
}
Any method which is accepting Comparable<T> type parameter will also accept AdvancedComparable<T> type parameter, but when the method tries to call compareTo, it will break if the feature you asked is implemented.
Suppose if compiler updated to recognize this issues and made to throw compile time error, that's fine, but it also has to support the legacy code. Remember the Generics case, many classes which altered to support generic type, supports Raw type too (Like List, Class etc). Just to support legacy code. But in our case it is difficult to do so, I feel.
Can not you use super Abstract Class which would implement doSuperStuff() and other concrete class could extend it to override other method.
You can always cast a subtype to a supertype, and invoke methods in the supertype.
However, there is a way to prevent overriding --
public interface SuperInterface
Object doSuperStaff(); // return value doesn't matter, can be null
public interface SubInterface extends SuperInterface
default Foo doSuperStaff() { ... }
Here, Foo is a package-private type. Subclasses of SubInterface (in different packages) have no way to override this method, because they can't access Foo.
It's also possible to use a private class Foo there.
Suppose, there are two java classes.
BaseA
public class BaseA extends ModuleBase{
public void doSomething{
//does something
}
}
BaseB
public class BaseB extends ModuleBase implements
SomeInterface {
public void doSomething{
//does something
}
}
SomeInterface
public interface SomeInterface {
public void doSomething();
}
so as you can see the only difference between BaseA & BaseB is that BaseB implements an interface. As far my understanding an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. It cannot be instantiated.
Questions:
it seems BaseA & BaseA would be same as the methods & code in them is same. correct?
Interface seems like a contract that spells out how software APIs interact with each other & have no effect on class functions. only purpose of interface is to enforce that BaseB has mandatorily implement doSomething, where as with BaseA, its optional & won't generate compile errors. if not, then why?
What difference implementing an interface make? I know you have to implement all methods of that particular interface but if can also you do that without the keyword implements InterfaceName as seen in BaseB Vs BaseA where we implemented exact same doSomething(). what difference having the keyword implements InterfaceName in class declaration make?
No. Classes in Java are the same when they have the same fully qualified name and when they were loaded from the same classloader. Java makes no attempt to look into methods and it doesn't compare method signatures.
Or to put it differently: Java doesn't support duck typing.
Usually, interfaces are used to make a bunch of classes easily interchangeable. So you have something that needs a certain functionality. Instead of typing this to a single class, you can use an interface. People using that service can then feed it with different classes, according to their needs, making the service much more flexible (and somewhat harder to understand).
It means you can use BaseB in any place where InterfaceName is expected. That makes BaseB (and everything derived from it) much more useful/powerful.
Example:
If you want to check passwords, you can write a PasswordService class. But that means everyone has to use this class and live with the limitations.
If you offer a PasswordService interface, then users of your code can have different implementations: They can get passwords from a file, a database, LDAP, ... or for unit tests, they can write a service that says yes or no to every password.
what difference having the keyword implements InterfaceName in class declaration make?
You can then cast to that interface.
Java is not duck-typed.
Even if your class has a method void run() like a Runnable, you still won't be able to give it to places that want a Runnable without implementing the interface.
new Thread(instanceOfMyNotRunnableClass); // won't compile
Two classes are not same by their code. The code may be same but classes are still different. Two classes with same code may behave similar but will not be same.
To understand purpose of Interface, you should understand concepts of Abstraction and Encapsulation. Interface not only provides a contract, also provides an abstraction over underlying classes. You may write an API that takes object of type Interface without bothering about actual class implementing the Interface.
You can use BaseB in place where InterfaceName but you should not. This makes your code rigid for using only BaseB, whereas you may write an utility that takes any class that has implemented the interface.
Well, I assume that SomeInterface declares "doSomething", right?
If that's the case, the benefit for you is that you can treat BaseB as SomeInterface. Let's say you have another class BaseC, which also implements SomeInterface, then this code is valid:
SomeInterface inter = new BaseB();
inter = new BaseC();
while this is not valid:
SomeInterface interr = new BaseA();
Your advantage is, that you do not have to know, if inter is BaseB() or BaseC(), because you simple work on the interface declared methods, no matter how the implementation excatly looks like.
Interface is used to make skeleton of your API. Like java.util.ArrayList and java.util.LinkedList both are classes which implement interface java.util.List.
So if you have method like below
void doSomething(java.util.List list){
}
You can pass java.util.ArrayList or java.util.LinkedList as per your requirment with no harm.You don't have to create two diff. methods where one accept java.util.ArrayList and another accept java.util.LinkedList
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
java Enum definition
Better formulated question, that is not considered a duplicate:
What would be different in Java if Enum declaration didn't have the recursive part
if language designers were to use simply Enum<E extends Enum> how would that affect the language?
The only difference now would be that someone coud write
A extends Enum<B>
but since it is not allowed in java to extend enums that would be still illegal.
I was also thinking about someone supplying jvm a bytecode that defines smth as extending an enum - but generics can't affect that as they all are erased.
So what is the whole point of such declaration?
Thank you!
Edit
for simplicity let's look at an example:
interface MyComparable<T> {
int myCompare(T o);
}
class MyEnum<E extends MyEnum> implements MyComparable<E> {
public int myCompare(E o) { return -1; }
}
class FirstEnum extends MyEnum<FirstEnum> {}
class SecondEnum extends MyEnum<SecondEnum> {}
what's wrong with this class structure? What can be done that "MyEnum<E extends MyEnum<E>>" would restrict?
This is a common question, and understandably so. Have a look at this part of the generics FAQ for the answer (and actually, read as much of the whole document as you feel comfortable with, it's rather well done and informative).
The short answer is that it forces the class to be parameterized on itself; this is required for superclasses to define methods, using the generic parameter, that work transparently ("natively", if you will) with their subclasses.
Edit: As a (non-)example for instance, consider the clone() method on Object. Currently, it's defined to return a value of type Object. Thanks to covariant return types, specific subclasses can (and often do) define that they return a more specific class, but this cannot be enforced and hence cannot be inferred for an arbitrary class.
Now, if Object were defined like Enum, i.e. Object<T extends Object<T>> then you'd have to define all classes as something like public class MyFoo<MyFoo>. Consequently, clone() could be declared to return a type of T and you can ensure at compile time that the returned value is always exactly the same class as the object itself (not even subclasses would match the parameters).
Now in this case, Object isn't parameterized like this because it would be extremely annoying to have this baggage on all classes when 99% of them aren't going to utilise it at all. But for some class hierarchies it can be very useful - I've used a similar technique myself before with types of abstract, recursive expression parsers with several implementations. This construct made it possible to write code that was "obvious" without having to cast everywhere, or copy-and-paste just to change concrete class definitions.
Edit 2 (To actually answer your question!):
If Enum was defined as Enum<E extends Enum>, then as you rightly say, someone could define a class as A extends Enum<B>. This defeats the point of the generic construct, which is to ensure that the generic parameter is always the exact type of the class in question. Giving a concrete example, Enum declares its compareTo method as
public final int compareTo(E o)
In this case, since you defined A to extend Enum<B>, instances of A could only be compared against instances of B (whatever B is), which is almost certainly not very useful. With the additional construct, you know that any class that extends Enum is comparable only against itself. And hence you can provide method implementations in the superclass that remain useful, and specific, in all subclasses.
(Without this recursive generics trick, the only other option would be to define compareTo as public final int compareTo(Enum o). This is not really the same thing, as then one could compare a java.math.RoundingMode against a java.lang.Thread.State without the compiler complaining, which again isn't very useful.)
OK, let's get away from Enum itself as we appear to be getting hung up on it. Instead, here is an abstract class:
public abstract class Manipulator<T extends Manipulator<T>>
{
/**
* This method actually does the work, whatever that is
*/
public abstract void manipulate(DomainObject o);
/**
* This creates a child that can be used for divide and conquer-y stuff
*/
public T createChild()
{
// Some really useful implementation here based on
// state contained in this class
}
}
We are going to have several concrete implementations of this - SaveToDatabaseManipulator, SpellCheckingManipulator, whatever. Additionally we also want to let people define their own, as this is a super-useful class. ;-)
Now - you will notice that we're using the recursive generic definition, and then returning T from the createChild method. This means that:
1) We know and the compiler knows that if I call:
SpellCheckingManipulator obj = ...; // We have a reference somehow
return obj.createChild();
then the returned value is definitely a SpellCheckingManipulator, even though it's using the definition from the superclass. The recursive generics here allow the compiler to know what is obvious to us, so you don't have to keep casting the return values (like you often have to do with clone(), for example).
2) Notice that I didn't declare the method final, since perhaps some specific subclasses will want to override it with a more suitable version for themselves. The generics definition means that regardless of who create a new class or how it is defined, we can still assert that the return from e.g. BrandNewSloppilyCodedManipulator.createChild() will still be an instance of BrandNewSloppilyCodedManipulator. If a careless developer tries to define it to return just Manipulator, the compiler won't let them. And if they try to define the class as BrandNewSloppilyCodedManipulator<SpellCheckingManipulator>, it won't let them either.
Basically, the conclusion is that this trick is useful when you want to provide some functionality in a superclass that somehow gets more specific in subclasses. By declaring the superclass like this, you are locking down the generic parameter for any subclasses to be the subclass itself. This is why you can write a generic compareTo or createChild method in the superclass and prevent it from becoming overly vague when you're dealing with specific subclasses.
I just started figuring out the difference between implicit and explicit interface implmentation in .Net. Since I come from a Java background the idea is still a bit confusing. I am hoping knowing which Java does will make it more obvious what the difference is. I am assuming the Java is explicit???
Nope Java is implicit. Explicit is where you are implementing multiple interfaces that have the same method signatures in them and you explicitly state which interface the implementation is for.
An example from MSDN:
public class SampleClass : IControl, ISurface
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}
}
Here we have two Paint() methods, one from each interface. In Java you can only have one Paint() implementation. In C# you have the option of implementing versions for each interface so you get different behaviour depending how the class is called.
So if I called:
SampleClass c = new SampleClass();
((IControl)c).Paint();
((ISurface)c).Paint();
I'd get "IControl.Paint" printed out followed by "ISurface.Paint" printed out.
In Java there is no distinction between explicit and implicit. If you have two interfaces that both declare a method with the same signature, and a class that implements both interface, then a method in the class with the correct signature implements the method in BOTH interfaces.