简体   繁体   中英

Passing Abstract Class in Java

Trying to call a static method from an abstract class inside an instanced class. This is a primitive coding example of what I'm trying to do, but not sure how to go about it.

DataSource myDataSource = new DataSource();
DataAdapterTest.initialize(myDataSource);

public abstract class DataAdapterTest extends DataAdapter {
    public static void initialize(DataSource d) {
        d.addDataAdapter(DataAdapterTest.class);
    }

    public static void onCreate() {
        does something here
    }
}

public class DataSource {
    public void addDataAdapter(Class<DataAdapter> c) {
        c.onCreate();
    }
}

Your problem is unclear. I'll answer to what I guess the problem is.

Signature compile error

I guess you have the following compile error:

The method addDataAdapter(Class) in the type Main.DataSource is not applicable for the arguments (Class)

Just use a wider signature for addDataAdapter()

public void addDataAdapter(Class<? extends DataAdapter> c) {

onCreate call

You seem to be trying to use polymorphism with static methods, which is not a good idea since static methods are relative to a class.

c.onCreate();

You can't directly call a method from the class this way, because c is a Class object instance, and does not have such a method. It is not the same as calling:

DataAdapterTest.onCreate();

You should pass an instance of the class instead of a Class object, and use instance methods instead of static methods. On this aspect, it is hard to give advice because we don't know what you're trying to achieve.

Design problem

Needless Class parameter

You commented:

I need the DataSource to be able to call a method of varying DataAdapter abstract classes

The code you gave here only uses one class extending DataAdapter . If you need several, then put at least 2 in your minimal example. As of right now, I don't see the need of passing on a class here. You could as well do the following:

DataSource myDataSource = new DataSource();
DataAdapterTest.initialize(myDataSource);

public abstract class DataAdapterTest extends DataAdapter {
    public static void initialize(DataSource d) {
        d.addDataAdapter();
    }

    public static void onCreate() {
        //does something here
    }
}

public class DataSource {
    public void addDataAdapter() {
        DataAdapterTest.onCreate();
    }
}

Needless static stuff

If everything in your DataAdapterTest class is static, then what is the purpose of extending DataAdapter ? You can't use any inherited stuff without an instance of your child class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM