简体   繁体   中英

abstract classes, send implementation to a method

I have 2 classes as follows.

public absract class myAbstracClass{

//various methods and stuff.

}

public class myImplmentationOfAbstractClass extends myAbstractClass {

//just implments a call to the abstract class in the constructor.
//no extrac functionality is added in this instance.
}

In a third class I have a method

public class someFunctionality{//

//default constructor

public static void myMethod(myAbstractClass abc)
//do stuff with abc

}

In my code I then call this method

public class doWork{

    public static void main(){

    //create my implmented class
    myImplmentationOfAbstractClass myABC = new myImplmentationOfAbstractClass();

    //send this class to my function

    someFunctionality.myMethod(myABC);//this causes an NPE

    }

    }

I'm obviously missing something, and I'm not finding it on google.

For now I've changed my method to accept a myImplementationOfAbstractClass object. But this seems bad new as I expect to need to use the abstract class again, and extnd it for specific instances.

Am I going about this incorrectly, or can I not send a subclass of a superclass to a method expecting a copy of the superclass?

thanks in advance.

David.

edit:

I just want to say thanks to everyone who has taken the time to answer. You are all correct. The problem was elsewhere.

It turns out that within my function I was declaring another 'temp object' and I was declaring its members in a bad order... took a while to find that one!

Once again, thanks guys, The process of writing the question was as helpfull as the responses. We all got to the same conclusion, at about the sime time (me I realised it just as you where posting the response I guess).

Error in your method myMethod .
this code

myImplmentationOfAbstractClass myABC = new myImplmentationOfAbstractClass();
someFunctionality.myMethod(myABC);//this causes an NPE  

cannt' throw NPE

您提供的代码片段没有问题,导致空指针异常的原因还有其他……可能是如果您检查堆栈跟踪信息,或者您可以准确地确定引起问题的行,则可以更好地帮助您确定问题。

第一个猜测:您的问题出在别处:如果将实参类型假定为实作的超类或接口,则将实作作为实参提供是没有错的。

I've just realised that the class that had the function in it wasn't building correctly, so the NPE was due to the method it was due to my stupidity in not setting a variable to null prior to using it!

So +1 to all those who bothered to answer. I realised this just as you guys where writing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM