How to call abstract class method in java

[亡魂溺海] 提交于 2019-12-30 08:33:30

问题


I want to call a method of an abstract class in my own class. The abstract class is:

public abstract class Call {

    public Connection getEarliestConnection() {
         Connection earliest = null;

         ...

         return earliest;
    }    
} 

I want to call the above method, and the calling class is:

public class MyActivity extends Activity {

    Connection c = new Connection();

    private void getCallFailedString(Call cal)
    {
        c = cal.getEarliestConnection();

        if (c == null) {
            System.out.println("** no connection**");
        } else {
            System.out.println("** connection");
        }
    }
}

Whenever I try to run the above class, it throws a NullPointerException on the line c = cal.getEarliestConnection(). Can anyone tell me how to resolve this problem?


回答1:


Firstly, Call an abstract class, therefore you cannot instantiate it directly. You must create a subclass, say MyCall extends Call which overrides any abstract methods in Call.

Getting a NullPointerException means that whatever you are passing in as an argument to getCallFailedString() hasn't been initialized. So after you create your subclass of Call, you'd have to instantiate it and then pass this in to your method, so something like:

class MyCall extends Call 
{ 
     //override any abstract methods here... 
}

Wherever you are calling getCallFailedString() would then require something above it like:

Call cal = new MyCall();
Activity activity = new MyActivity();
activity.getCallFailedString(cal);



回答2:


Looks like the Call cal is null before it is passed into the function getCallFailedString. Make sure you extend Call and instantiate the extended class and pass it into getCallFailedString.




回答3:


Make sure your object "cal" is initialized and not null. Also, you won't be able to instantiate a Call object(as its an abstarct class). Instead, declare class Call as an interface and implement its method getEarliestConnection(), in your class.



来源:https://stackoverflow.com/questions/8722407/how-to-call-abstract-class-method-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!