简体   繁体   中英

NullPointerException When trying to call Abstract class - Java

When my submit button is clicked it validates input fields depending on which fields were used, then calls the writeItemToFile() method.

private void btnSubmit_actionPerformed(ActionEvent e)
{
    if (validateInput()){
        if (enabledFields == "music")
            createMusicItem();
        else
            if (enabledFields == "product")
                createProductItem();}
    writeItemToFile();
}//btnSubmit_actionPerformed

The writeItemToFile() method is small and frankly could be skipped, but is needed for my assignment. It calls the write(Item item) method in my Inventory class. It sends along the item declaration at the top of my code.

 Item item;

The problem is that the Item class is abstract so when it's passed it gives me a NullPointerException. Below is my write(Item item) method just for good measure. My question is this, is there a way I have to instantiate the abstract class? How do I avoid this method.

public void write(Item item)
{
    invFilename = item.getFileName();
    File inventoryFile = new File(invFilename);

    try
    {
        invWriter = new FileWriter(inventoryFile, true);
    } // try

    catch (IOException e)
    {
        System.out.println("ERROR: File " + invFilename + "could not opened: "
                + e.getMessage());
    }//catch

    try
    {
        invWriter.write(item.getFileRecord());
    }//try

    catch (IOException e)
    {
        System.out.println("ERROR: Product " + item.getFileRecord()
                + "could not be written to file " + invFilename + ": "
                + e.getMessage());
    }//catch
}//write(Item item)

Please be gentle.

Error message:

 Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Inventory.write(Inventory.java:13)
at AddItemFrame.writeItemToFile(AddItemFrame.java:575)
at AddItemFrame.btnSubmit_actionPerformed(AddItemFrame.java:500)
at AddItemFrame.access$1(AddItemFrame.java:492)
at AddItemFrame$3.actionPerformed(AddItemFrame.java:217)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

A NullPointerException triggered by your write method is likely to be caused by a null argument of type Item , specifically on:

item.getFileName(); --> invoking method of null Object .

It could also be caused by:

new File(invFilename) --> initializing new File with null argument (if item is not null , but item.getFileName() is).

... etc.

Nothing to do with the fact that Item is an abstract class.

Note

As mentioned by others in the comments, String contents comparison is done by equals , not the == operator.

the Item class is abstract

That means you cannot have an object of this class. You need to extend the abstract class and pass an object of your new class.

Check here : Abstract classes cannot be instantiated, but they can be subclassed

"The problem is that the Item class is abstract so when it's passed it gives me a NullPointerException."

Abstract does not mean null . An abstract class cannot be directly instantiated , but its sub-classes may. Therefore it is perfectly legal to have a function such as

public String getAbstrClassesToString(AnAbstractClass abstract_class)  {
   try  {
      return  abstract_class.toString();
   }  catch(NullPointerException npx)  {
      if(abstract_class == null)  {
         throw  new NullPointerException("abstract_class");
      }

      //Just in case the toString() throws an NPX
      throw  npx;
   }
}

Now you could call this with

getAbstrClassesToString(null);

which will obviously result in a NullPointerException , or you could call this with

getAbstrClassesToString(new ConcreteSubClassOfAnAbstractClass());

which is perfectly legal, and obviously not null.

In other words, your NullPointerException problem is unrelated to abstract-ness.

More information: https://www.google.com/search?q=abstract+class+java+tutorials

The object of type Item that is being passed must be instantiated.

As pointed out by others, you cannot simply create it via:

Item item = new Item(); // this does not work!

However, you can extend the class and create all the abstract methopds required and then instantiate the new class.

class ItemB extends Item
{
  ...
}

Then you can work with the new class,

ItemB item = new ItemB();

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