Class subA is the subclass of class A. I tried to override a method but Somehow it doesn't let me override it. why is that? Is it because of the argument in the parameter?
Error message read:
name clash: add(E#1) in subA and add(E#2) in A have the same erasure, yet neither overrides the other
where E#1,E#2 are type-variables:
E#1 extends Object declared in class subA
E#2 extends Object declared in class A
SuperClass A:
public class A <E> {
public void add(E toInsert) {...}
}
SubClass subA:
public class subA <E> extends A {
//overrides the method from A class
public void add (E toInsert) <-- doesn't let me overrides
{...}
}
You are subclassing the raw A class (generic parameters have not been provided), which by definition from the Java Language Specification strips all generic information from the superclass. This means that your subclass generic method is incompatible with the (now) non-generic superclass method.
Provide a generic parameter for A by passing through the generic parameter for your subclass:
public class subA <E extends Comparable<E>> extends A<E> {
#Override
public void add (E toInsert) {
// ...
}
}
Function Overriding in C++ Programming
If base class and derived class have member functions with same name and arguments. If you create an object of derived class and write code to access that member function then, the member function in derived class is only invoked, i.e., the member function of derived class overrides the member function of base class. This feature in C++ programming is known as function overriding.
Example to demonstrate function overriding in C++ programming
Accessing the Overridden Function in Base Class From Derived Class
To access the overridden function of base class from derived class, scope resolution operator ::. For example: If you want to access get_data() function of base class from derived class in above example then, the following statement is used in derived class.
A::get_data; // Calling get_data() of class A.
It is because, if the name of class is not specified, the compiler thinks get_data() function is calling itself.
User of scope resolution operator in overridden function
- See more at: http://www.programiz.com/cpp-programming/function-overriding#sthash.7UmWybpS.dpuf
public class subA <E extends A> extends A {
because E is defined in A you need to have your generic extend the same generic type of A is. I'm sure someone would have a better explanation than mine but I know this way works.
Related
Given an interface like this
public interface MyInterface1<T extends MyAbstractClass> {
...
}
I want to make another interface MyInterface2 taking a MyInterface1 as a generic type and in MyInterface2 I want to reference the actual types of the actual MyInterface1
public interface MyInterface2<INTERFACE extends MyInterface1<MYCLASS>> {
MYCLASS returnInstanceOfMyClass();
}
So I want to say that method "returnInstanceOfMyClass" returns the actual T of the actual MyInterface1 given to MyInterface2.
The thing is that I am not allowed to write the following
public interface MyInterface2<INTERFACE extends MyInterface1<MYCLASS>> {
I am allowed to write
public interface MyInterface2<INTERFACE extends MyInterface1<?>> {
but then I am not able to reference the actual type of T in MyInterface1 in the method signature in MyInterface2 - because I have given it no name to be used when referencing.
I want to be able to do the following in a type-safe way
class MyClass extends MyAbstractClass {
...
}
MyClass c = new MyInterface2<MyInterface1<MyClass>>.returnInstanceOfMyClass();
No casting to MyClass should be necessary, because it can see that the actual class of MyInterface1 given to MyInterface2 is MyClass, and that is what is returned from returnInstanceOfMyClass.
How to do that?
You need a second generic parameter:
public interface MyInterface2<U estends MyAbstractClass, T extends MyInterface1<U>> {
U returnInstanceOfMyClass();
}
I have a class (called SubClass for simplicity) that extends SuperClass and implements IClass.
I know that you can call SuperClass' methods by using super.method(), but is it possible to call a method from SubClass which it implements from IClass?
Example:
public class SuperClass {
public void method(){
implementedMethod();
}
}
Subclass:
public class SubClass extends SuperClass implements IClass{
public void implementedMethod() {
System.out.println("Hello World");
}
}
IClass:
public interface IClass {
public void implementedMethod();
}
I would like to call SubClass' implementedMethod() (Which it gets from IClass) from SuperClass
How would I go about doing that?
You can make the super class abstract:
public abstract class SuperClass implements IClass {
public void method(){
implementedMethod();
}
}
Given the types above, anExpressionOfTypeSubClassOrIClass.implementedMethod() must be used. Note that the Type of an expression - the view it provides - must have the method intended to be used. In this case, an expression of type SuperClass cannot be used here because it has no declared implementedMethod member.
One approach - and arguably the preferred approach - is to use abstract methods. Even though abstract methods are not strictly required for Polymorphism they describe scenarios such as this where a subclass should provide the implementation. (The abstract methods could be replaced with empty method expecting - but not requiring - to be overridden in sublcasses, but why not use abstract for its designed purpose?)
abstract class SuperClass implements IClass {
// Don't implement this, but declare it abstract
// so that we can conform to IClass as well
public abstract void implementedMethod();
public void method () {
// Now this object (which conforms to IClass) has implementedMethod
// which will be implemented by a concrete subclass.
implementedMethod();
}
}
This has the "negative" aspects that SuperClass cannot be directly instantiated (it is abstract, after all) and that SuperClass must implement (or, as shown, delegate out via abstract) the expected signature. In this case I also chose to make SuperClass implement IClass even though it's not strictly required because it guarantees that the SuperClass and all subclasses can be viewed as an IClass.
Alternatively, remember that Types of Expressions are just views of objects and are not necessarily the same as the actual Concrete Type of object. While I would advise against using the following code because it loses some type-safety, I think it shows the important point.
class SuperClass {
public void method () {
// We try to cast and NARROW the type to a
// specific "view". This can fail which is one
// reason why it's not usually appropriate.
((IClass)this).implementedMethod();
}
}
class SubClass extends SuperClass implements IClass {
// ..
}
class BrokenSubClass extends SuperClass () {
}
// OK! Although it is the SAME OBJECT, the SuperClass
// method can "view" the current instance (this) as an IClass
// because SubClass implements IClass. This view must be
// explicitly request through a cast because SuperClass itself
// does not implement IClass or have a suitable method to override.
(new SubClass()).method();
// BAD! ClassCastException, BrokenSubClass cannot be "viewed" as IClass!
// But we didn't know until runtime due to lost type-safety.
(new BrokenSubClass()).method();
The only way to call that method would be to create an object of type SubClass (in SuperClass) and call subClassInstance.implementedMethod().
I also want to stress that this is very inelegant. As stated in a comment on your question, you should reconsider your class designs if your superclass needs to call a subclass method.
I started studying Java-generics. And I have some misunderstanding of the generics syntax and its meaning. I beg to treat with understanding if my question seems too trivial.
You can write:
public class MyClass<SomeClass> {}
and you can write:
public class MyClass<C extends SomeClass> {}
and you can write also:
public class MyClass<? extends SomeClass> {}
What is the difference between these cases?
The first case is absolutely clear to me: you can use instance of SomeClass and instance of his subclasses as class's parameter for MyClass.
I think that in this case you can only use instance of MyClass's subclasses
The same: only use instance of MyClass's subclasses as class's parameter for MyClass.
Are my guesses right or not? And especially what is the difference between the using of the second and third cases?
Thanks in advance for explanation!
Well the difference is you cant use ? in generic class declaration
public class MyClass<? extends SomeClass> {} // this isn't valid
The above declaration leads to compiler error.
From Documentation:
A generic class is defined with the following format:
class name { /* ... */ } The type parameter section,
delimited by angle brackets (<>), follows the class name. It specifies
the type parameters (also called type variables) T1, T2, ..., and Tn.
public class MyClass<C extends SomeClass> {}
In this declaration C is a type-argument which could be of type SomeClass or any of its SubClass's.
Example :
Class SomeOtherClass extends SomeClass {
}
MyClass clazz = new MyClass<SomeOtherClass>();
MyClass clazz = new MyClass<SomeClass>();
Recently came across an interesting feature, which, though, can result in a unexpected output of Eclipse "add unimplemented methods" feature. What is the "googl-able" name of the language concept behind this "occasional implicit implementation"?
I wouldn't expect the code below to compile but it did and is working
interface CallmeIfc {
public void callme();
}
class CallmeCode {
public void callme() {
// implementation
}
}
class CallmeImpl extends CallmeCode implements CallmeIfc {
// empty class body
}
public static void main(String[] args) {
CallmeIfc me = (CallmeIfc) new CallmeImpl();
me.callme(); // calls CallmeCode.callme()
}
In CallmeImpl, the public callme() method is inherited from CallmeCode, so CallmeImpl respects the contract defined in the CallmeIfc.
Then, in your main() method, polymorphism allows you to assign a subclass instance (CallmeImpl) to a superclass or superinterface reference - in this particular case, the "me" reference, of type CallmeIfc (you have a typo here, BTW).
Actually this looks like a compiler bug to me: The Java Language Specification writes:
An instance method m1 declared in a
class C overrides another instance
method, m2, declared in class A iff
all of the following are true:
C is a subclass of A.
The signature of m1 is a subsignature (§8.4.2) of the signature of m2.
Either
m2 is public, protected or declared with default access in the same package as C, or
m1 overrides a method m3, m3 distinct from m1, m3 distinct from m2, such that m3 overrides m2.
In your case, the first condition is not satisfied: The method callme is declared in class CallMeCode, which is not a subtype of CallmeIfc.
Edit: Bobah is right, the Spec distinguishes between implementing and overriding. In fact, it actually mandates the observed behaviour:
Unless the class being declared is
abstract, the declarations of all the
method members of each direct
superinterface must be implemented
either by a declaration in this class
or by an existing method declaration
inherited from the direct superclass,
because a class that is not abstract
is not permitted to have abstract
methods
The Spec does not explain why.
Although CallmeCode class doesn't implement the CallmeIfc interface, it provides the necessary implementation. It is as if class CallmeCode implements the interface. It would have worked also with this code:
interface CallmeIfc {
public void callme();
}
class CallmeCode implements CallmeIfc {
public void callme() {
// implementation
}
}
class CallmeImpl extends CallmeCode implements CallmeIfc {
// empty class body
}
In your case this is fine because class CallmeCode has a method callme. If the method would have been named different it wouldn't compile.
I am trying to define an abstract class implementing Comparable. When I define the class with following definition:
public abstract class MyClass implements Comparable <MyClass>
subclasses have to implement compareTo(MyClass object). Instead, I want every subclass to implement compareTo(SubClass object), accepting an object of its own type. When I try to define the abstract class with something like:
public abstract class MyClass implements Comparable <? extends MyClass>
It complains that "A supertype may not specify any wildcard."
Is there a solution?
It's a little too verbose in my opinion, but works:
public abstract class MyClass<T extends MyClass<T>> implements Comparable<T> {
}
public class SubClass extends MyClass<SubClass> {
#Override
public int compareTo(SubClass o) {
// TODO Auto-generated method stub
return 0;
}
}
Apart from the mechanical difficulties you're encountering declaring the signatures, the goal doesn't make much sense. You're trying to establish a covariant comparison function, which breaks the whole idea of establishing an interface that derived classes can tailor.
If you define some subclass SubClass such that its instances can only be compared to other SubClass instances, then how does SubClass satisfy the contract defined by MyClass? Recall that MyClass is saying that it and any types derived from it can be compared against other MyClass instances. You're trying to make that not true for SubClass, which means that SubClass does not satisfy MyClass's contract: You cannot substitute SubClass for MyClass, because SubClass's requirements are stricter.
This problem centers on covariance and contravariance, and how they allow function signatures to change through type derivation. You can relax a requirement on an argument's type—accepting a wider type than the supertype's signature demands—and you can strengthen a requirement on a return type—promising to return a narrower type than the supertype's signature. Each of these freedoms still allows perfect substitution of the derived type for the supertype; a caller can't tell the difference when using the derived type through the supertype's interface, but a caller using the derived type concretely can take advantage of these freedoms.
Willi's answer teaches something about generic declarations, but I urge you to reconsider your goal before accepting the technique at the expense of semantics.
see Java's own example:
public abstract class Enum<E extends Enum<E>> implements Comparable<E>
public final int compareTo(E o)
on seh's comment: usually the argument is correct. but generics makes type relations more complicated. a SubClass may not be a subtype of MyClass in Willi's solution....
SubClassA is a subtype of MyClass<SubClassA>, but not a subtype of MyClass<SubClassB>
type MyClass<X> defines a contract for compareTo(X) which all of its subtypes must honor. there is no problem there.
I'm not sure that you need the capture:
First, add the compareTo to the abstract class...
public abstract class MyClass implements Comparable <MyClass> {
#Override
public int compareTo(MyClass c) {
...
}
}
Then add the implementations...
public class MyClass1 extends MyClass {
...
}
public class MyClass2 extends MyClass {
...
}
Calling compare will call the super type method...
MyClass1 c1 = new MyClass1();
MyClass2 c2 = new MyClass2();
c1.compareTo(c2);
public abstract class MyClass<T> implements Comparable<T> {
}
public class SubClass extends MyClass<SubClass> {
#Override
public int compareTo(SubClass o) {
// TODO Auto-generated method stub
return 0;
}
}
Found another solution:
Define an interface on the fields which make up the comaprable (e.g ComparableFoo)
Implement the interface on the parent class
Implement Comparable on the parent class.
Write your implementation.
Solution should look like this:
public abstract class MyClass implements ComparableFoo,Comparable<ComparableFoo> {
public int compareTo(ComparableFoo o) {
// your implementation
}
}
This solution implies that more things might implement ComparableFoo - this is likely not the case but then you're coding to an interface and the generics expression is simple.
I know you said you want "compareTo(SubClass object), accepting an object of its own type", but I still suggest declaring the abstract class like this:
public abstract class MyClass implements Comparable <Object>
and do an instanceof check when overriding compareTo in MySubClass:
#Override
public int compareTo(Object o) {
if (o instanceof MySubClass)) {
...
}
else throw new IllegalArgumentException(...)
}
similarly to 'equals' or 'clone'