User from Stackoverflow asked this question, unfortunately doesn't have answer which can explain situation.
Why enum can't extend another class while all other classes can
I have the same question. Java also tells that it is multyple extends and it is not supports. Java documentation.
But this part confusing me. If any class by default extends Object class(Main class in Java), and any new class can extend another class (except Object class), but any new Enum can't? Why?
Any Enum extends Enum class by default and for special for enum can't extend more classes, and if say it is program way, will be more understandable. But in documentation was writen can't extends because it is multyple classes. Maybe Documentation isn't correct? If someone can explain this part, please explain this.
Thank you!
As the comments on the question you linked to explain, all classes do not extend Object.
A class:
class Foo { }
implicitly extends Object, but a class:
class Bar extends Foo { }
Just extends Foo.
It is also a descendant of Object via Foo.
So an enum implicitly extends Enum, and can't extend anything else.
Enums are final classes, so nothing can extend them.
From the documentation you have linked:
Note: All enums implicitly extend java.lang.Enum. Because a class can
only extend one parent (see Declaring Classes), the Java language does
not support multiple inheritance of state (see Multiple Inheritance of
State, Implementation, and Type), and therefore an enum cannot extend
anything else.
Basically Enum has complier magic built in, that actually has the complier extend the Enum class from the java.lang.Enum.
Java doesn't support multiple inheritance of classes and hence you cant have extended Enums.
See this from the spec jls-8.9 as well.
An enum type is implicitly final unless it contains at least one enum
constant that has a class body.
It is a compile-time error to explicitly declare an enum type to be
final.
Related
Can, and if yes how, I access the generic parameter of another generic parameter, without also specifying it?
The example below is simplified from my current situation. All members and methods are omitted as they aren't relevant to the situation. LibraryRepository is a JPA/Spring-Type expecting an ENTITY and an ID.
abstract class AbstractEntity<ID> {}
class ConcreteEntity extends AbstractEntity<Long> {}
interface AbstractRepository<ENTITY extends AbstractEntity<?????>> extends LibraryRepository<ENTITY, ?????> {}
//Desired declaration:
interface ConcreteRepository extends AbstractRepository<ConcreteEntity> {}
Without specifying Long on AbstractRepository, what to write instead of the two ?????, if that is at all possible?
For the sake of question-scope, please answer the question regarding generics, not how to implement spring-repositories in a better way. I'm glad for hints about that in the comments though.
interface AbstractRepository<ENTITY extends AbstractEntity<?????>> extends LibraryRepository<ENTITY, ?????> {}
One (particularly useful) way of thinking about generics is that they link types together. If you declare a new typevar and use it in only one place, because of erasure, that is effectively useless. Use it in two places and now you've told the compiler that the two places you used your T are linked: They can be anything, as long as they are the same thing.
This way of thinking also provides some insight here: Clearly you want your first ????? to be linked to your second ?????: For them to be equal.
The way to do that, then, is to declare a new typevar and use it:
interface AbstractRepository<ENTITY extends AbstractEntity<Q>, Q>
extends LibraryRepository<ENTITY, Q> {}
Unfortunately, that means AbstractRepository now gained a type variable, and I gather you didn't want that to happen.
Unfortunately, java has no way to link types without a type variable.
As a general rule of thumb, if you mix class hierarchies (things extending things implementing things), and lots of generics, you end up with looooots of generic parameters, and some of those will feel like DRY violations. The solution is to either accept it, or to not do one of those two things (Use composition over inheritance, or reduce the type variables you're using, or move them to methods instead), or to use a bunch of hacky reflection and 'warning-casts' (where you cast things to a typevar, which doesn't actually typecheck anything and tends to result in ClassCastExceptions in bizarre places: Places that don't even have a cast anywhere in the line, and not the place with the faulty code. Resulting in long and arduous bughunting exercises.
Maybe this is what you're trying to avoid, but I think you'd specify the generic parameter of your AbstractEntity as a parameter in AbstractRepository, something like this:
interface LibraryRepository<ENTITY, ID> {}
abstract class AbstractEntity<ID> {}
class ConcreteEntity extends AbstractEntity<Long> {}
interface AbstractRepository<ENTITY extends AbstractEntity<ID>, ID>
extends LibraryRepository<ENTITY, ID> {}
interface ConcreteRepository extends AbstractRepository<ConcreteEntity, Long> {}
I don't know how otherwise the compiler would be able to type-check the generic parameters for LibraryRepository.
In JDK 11 I'm creating a generic class called "Collection" such that whatever type is provided for the type parameter must implement the Comparable interface. The class declaration is currently as follows:
public class Collection <T extends Comparable<T>>
Originally I thought the class declaration should be this:
public class Collection <T implements Comparable<T>>
but JDK didn't like that.
So my question is why the class declaration is the former rather than the latter. Don't we extend classes and implement interfaces?
With respect to the syntax of bounds declaration, the language architects who added generics in Java 5 faced the following choice:
Mirror the declaration structure (with separate extends and implements bounds), or
Choose one form for upper-bounded types (e.g., T extends Foo, T <: Foo, etc.)
The latter was (sensibly, IMO) viewed as the more pragmatic choice, as at the point of declaring a type variable, whether the supertype happens to be a class or an interface is not material, and having a fussy syntax that required clients to use exactly the right keyword (and would have made compound bounds like <T extends ArrayList implements Serializable> even uglier) would likely be viewed as just making things harder to use with no actual benefit to either writers or readers of code.
Such decision often come about as a language is evolved, where strict consistency with precedent would only make things more difficult for no good benefit, and so language designers sometimes (after carefully considering the pros and cons of both alternatives) choose to break with precedent for the sake of a better result.
Collection is already in java.util. Creating another class with that name is going to confuse everybody; I suggest you pick something else.
Generics is about types in general. The word extends is used, and this kinda mirrors the same use of that keyword in, for example, class Foo extends Bar, but it's not quite the same meaning. The point is, the spec says it is extends and not implements regardless of what comes after, and there's not much point in going any further than 'spec says so' on this one.
Would you therefore want implements E or extends E, given that E may be a class or an interface? Unless you want a third keyword (possibly context-sensitive) then it doesn't make sense to distinguish.
Is an interface a special kind of class or can you say that an interface isn't a class at all?
An interface isn't a class, but you could say that both interfaces and classes are types.
From the Java specification:
In the Java programming language, every variable and every expression has a type that can be determined at compile-time. The type may be a primitive type or a reference type. Reference types include class types and interface types.
Notice though there is a special class called Class<T> that can represent both classes and interfaces:
Instances of the class Class represent classes and interfaces in a running Java application.
The fact that an interface is represented by a Class instance where isInterface is true could give you the impression that an interface is just a special type of class. However this is not the case.
No, an interface is not a class in Java.
An interface is a type and all reference types (i.e. non-primitive types) handle quite similarly in Java. Often when people say "class" they are actually referring to a "reference type".
What might be confusing you is that an interface definition is stored in a .class file, but that's just a technical artifact of Java. In fact all reference type definitions (classes, interfaces, annotations, enums) are stored in .class files in Java.
The concept of interfaces comes from Abstract Classes, where as abstract classes contains prototypes of method (or abstract methods) and can have few of its methods defined also, while interfaces contains only the prototypes(or signature) of method or abstract methods, whose definition is to be provided by the implementing class.
so from the above statement it is clear that interfaces are like 100 percent abstract classes where -
none of its method is defined.
mentioning it again interfaces are like 100 percent abstract classes but not the classes.
"Interfaces are contracts for what a class can do"
A reason for introducing interface is, we can extend only single class but interface brought a new thing implement in java so we can implement thousands of interface.So we can not say that it is a class.
you can get more about this Here!
Interface is just a contract which all implementing classes should follow.
An interface is something like a template which cannot make an impact until a class implements it.
Yes, an interface is an instance of java.lang.Class. If you have a Class you can interrogate it to see if it is an interface: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isInterface()
An interface(is a group of related methods with empty bodies.) is just an interface. Its not a class(A class is the blueprint from which individual objects are created).
notice that you define an interface like this
interface Bicycle {....}
and a class is defined like this
class MyBMX implements Bicycle{...}
So an Interface is an Interface and NOT a class
yes interface is a kind of class.simply say in class methods and data present also in interface method(only abstract method) and data(only static and final) present.
for more watch it
https://www.youtube.com/watch?v=qgBv1_Plldo&list=PLbRMhDVUMngcx5xHChJ-f7ofxZI4JzuQR&index=21&t=13:52
Can someone tell me what the differences between the first and second codes are?
MaxPQ stands for priority queue, which is a collection of "Key" objects that can be compared with each other.
Code 1:
public class MaxPQ<Key extends Comparable<Key>>{
...
}
Code 2:
public class MaxPQ<Key implements Comparable<Key>>{
...
}
The second code doesn't compile, but it is not intuitive to me why we need to extend instead of implement interfaces when using a generic.
The difference is pretty straightforward: second code snippet does not compile and never will. With generics you always use extends, for both classes and interfaces. Also super keyword can be used there, but it has different semantics.
There is no implements in generics. The second code is invalid. You probably confusing with :
public class MaxPQ implements Comparable<Key> {
...
}
I assume it was decided to use extends for both interfaces and classes, because in the case of generic class declaration it does not make any difference is type argument bound to interface or to class.
Of course meaning of extends is quite different from its typical usage in class definition. Angelika Langer do have nice text about different meanings of extends in Java: Does "extends" always mean "inheritance"?
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.