How to call an abstract class method in java

I want to call an abstract class method in my class. Abstract class:

public abstract class Call { public Connection getEarliestConnection() { Connection earliest = null; ... return earliest; } } 

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

 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 specified class, it throws a NullPointerException in the string c = cal.getEarliestConnection() . Can someone tell me how to solve this problem?

+7
source share
3 answers

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

Getting a NullPointerException means that everything you pass as the argument to getCallFailedString() not been initialized. Therefore, creating your subclass of Call, you must create an instance of it, and then pass it to your method, for example:

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

Wherever you call getCallFailedString() , then you need something above it, for example:

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

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

+1
source

Make sure your cal object is initialized and non-zero. In addition, you cannot create an instance of the Call object (as its class abstarct). Instead, declare the Call class as an interface and implement its getEarliestConnection () method in your class.

-2
source

All Articles