如何在Java中调用抽象类方法 [英] How to call abstract class method in java

查看:550
本文介绍了如何在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");
        }
    }
}

无论何时我尝试运行上一类,它将在 c = cal.getEarliestConnection()行上引发NullPointerException。谁能告诉我如何解决这个问题?

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?

推荐答案

首先,致电抽象类,因此您不能直接实例化它。您必须创建一个子类,例如 MyCall扩展了Call ,它覆盖了Call中的任何抽象方法。

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.

获取 NullPointerException 意味着您作为 getCallFailedString()的参数传入的任何内容都尚未初始化。因此,在创建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... 
}

无论您何时呼叫 getCallFailedString(),都需要上面的内容:

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

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

这篇关于如何在Java中调用抽象类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆