Link to home
Start Free TrialLog in
Avatar of uxlin
uxlin

asked on

Java - "YList is abstract; cannot be instantiated"

Hi, I've a Java abtract class "YList", and in many methods I need to return an instance of YList, Java doesn't allow using "new YList()", can anyone tell me how to achieve this?

The program's like this:
public abstract class YList<E>() {
    public YList<E> trim() {
        result = new YList<E>(); // Not allowed by Java

        result.trimThis();
        result.trimThat();

        return result;
    }
}

trim() is just one of the many methods where it's needed.

Thanks in advance!
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

You can't make an instance of an abstract class

Abstract classes (by definition) need to be extended as they have abstract methods that must be overriden

If your class has no abstract methods, then you should be able to get rid of the "abstract" bit in the class definition line like:

public class YList<E>() {
 
Avatar of uxlin
uxlin

ASKER

Thank you, yeah I learned the hard way that I can't make an instance of an abstract class.

Is there any other way that the method can be written?

I know for trim() I can use a abstract duplicate() method, but there are lots of other methods where duplicate() would be inefficient.
You could have the trim() method actually act on the current instance...

  public void trim() {
        this.trimThis();
        this.trimThat();
    }

if you want to return the changed list (for chaining purposes) you could do:

  public YList<E> trim() {
        this.trimThis();
        this.trimThat();
        return this ;
    }

It would then be up to the user to make a copy if they want to keep an untrimmed version of the list...

Tim
Avatar of uxlin

ASKER

Thanks you for your comment, but trim() is like the trim() in String, cannot change the current instance. If it can change the current instance, of course thing are much easier.
Avatar of uxlin

ASKER

*Thanks you for your comment = Thank you for your comments
trim would have to be defined in the concrete class then, not in the abstraction...

Tim
Avatar of uxlin

ASKER

It, and many other similar methods need to be defined in the abstract class.

I'm wondering if there's anything like:
new this.type();

'cause appearantly we can't use:
new this();
you might be able to do

    YList<E> result = (YList<E>)this.clone() ;

To make a copy of the current list...
ASKER CERTIFIED SOLUTION
Avatar of Rytmis
Rytmis

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of uxlin

ASKER

Thank you so much!