user2415855
user2415855

Reputation:

Overriding method

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    
{...}  

}

Upvotes: 1

Views: 176

Answers (3)

venkateswara reddy
venkateswara reddy

Reputation: 1

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

Upvotes: 0

Bohemian
Bohemian

Reputation: 425318

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) {
        // ...
    }
}

Upvotes: 7

ug_
ug_

Reputation: 11440

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.

Upvotes: -4

Related Questions