Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call abstract class method in java

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?

like image 455
shiv1229 Avatar asked Jan 04 '12 05:01

shiv1229


2 Answers

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);
like image 73
Yuushi Avatar answered Oct 18 '22 20:10

Yuushi


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.

like image 35
poy Avatar answered Oct 18 '22 20:10

poy