java中如何调用抽象类方法
我想在我自己的类中调用抽象类的方法。抽象类是:
public abstract class Call {
public Connection getEarliestConnection() {
Connection earliest = null;
...
return earliest;
}
}
我想调用上面的方法,调用类是:
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");
}
}
}
每当我尝试运行上面的类时,它都会在 c = cal.getEarliestConnection()
行上抛出 NullPointerException。谁能告诉我如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,
调用
一个抽象类,因此不能直接实例化它。您必须创建一个子类,例如MyCall extends Call
,它会覆盖 Call 中的任何抽象方法。获取
NullPointerException
意味着您作为参数传递给getCallFailedString()
的任何内容都尚未初始化。因此,在创建 Call 的子类之后,您必须实例化它,然后将其传递给您的方法,因此类似于:无论您在哪里调用
getCallFailedString()
,都需要上面的内容,例如:Firstly,
Call
an abstract class, therefore you cannot instantiate it directly. You must create a subclass, sayMyCall extends Call
which overrides any abstract methods in Call.Getting a
NullPointerException
means that whatever you are passing in as an argument togetCallFailedString()
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:Wherever you are calling
getCallFailedString()
would then require something above it like:看起来
Call cal
在传递给函数getCallFailedString
之前为 null。确保扩展Call
并实例化扩展类并将其传递给getCallFailedString
。Looks like the
Call cal
is null before it is passed into the functiongetCallFailedString
. Make sure you extendCall
and instantiate the extended class and pass it intogetCallFailedString
.确保您的对象“cal”已初始化且不为空。此外,您将无法实例化 Call 对象(作为其抽象类)。相反,将 Call 类声明为接口并在类中实现其方法 getEarliestConnection()。
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.