Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't classes first class objects in Java?

Tags:

java

generics

Can somebody explain to me why classes are not first class objects in Java? There are certain patterns that would work really well if it did and I'm constantly writing factory classes with getters and setters and just adding unnecessary cruft to classes just so I can get around to passing instances to methods instead of actual classes to factor out generic bits of code. For example:

public class AsyncBookSearch extends AsyncTask<String,BookItem,Void> {

    public ListView list;
    public AmazonItemAdapter<BookItem> adapter;
    public AsyncBookSearch(ListView l,AmazonItemAdapter<BookItem> ad) {
        list = l;
        adapter = ad;
    }

    @Override
    protected Void doInBackground(String... keywords) {
        // TODO Auto-generated method stub
        new BookSearch(keywords[0],list,adapter).parse();
        return null;
    }
}

I have several such classes and if I want to make the whole thing generic then the stuff in doInBackground() will lead to several extra methods and other kinds of duplication in argument passing which wouldn't be a problem if I could write the following:

public class AsyncItemSearch<T extends GenericItemSearch<S>,S extends GenericItem> extends AsyncTask<String,T,Void> {

    public ListView list;
    public AmazonItemAdapter<S> adapter;
    public AsyncBookSearch(ListView l,AmazonItemAdapter<S> ad) {
        list = l;
        adapter = ad;
    }

    @Override
    protected Void doInBackground(String... keywords) {
        // TODO Auto-generated method stub
        new T(keywords[0],list,adapter).parse();
        return null;
    }
}

Currently I can't write code like that in Java. I have to introduce unnecessary coupling into pretty much every class involved and this just makes things more convoluted because now not only does each instance need to worry about it's own state but also about state in objects completely unrelated to it's task.

like image 548
David K. Avatar asked Dec 04 '22 23:12

David K.


1 Answers

I don't think your question is really about Classes being "first class" objects. I suspect it really has to do with how java handles generics. I think you need to understand type erasure: in your example you essentially want to write something like

void foo<T>{
  T bar = new T();
}

but this is not possible, because at run time, there is no information about what class T actually is, due to type erasure:

When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.

like image 131
Peter Recore Avatar answered Dec 30 '22 02:12

Peter Recore