Solved Cannot instantiate the type Listener

Discussion in 'Spigot Plugin Development' started by Artourious, Jan 22, 2020.

  1. Im trying to be able to track a player using a compass. I am very new to coding and don't know how to fix this error "Cannot instantiate the type Listener."

    Main
    Code (Java):
    package me.artourious.compasslocator;

    import org.bukkit.event.Listener;
    import org.bukkit.plugin.java.JavaPlugin;

    public class Main extends JavaPlugin implements Listener{

           public void onEnable(){
           Listener listener = new Listener(this);
           getServer().getPluginManager().registerEvents(listener, this);
       
               Main cpmain = new Main();
               Listener listener1 = new Listener(cpmain);
               getServer().getPluginManager().registerEvents(this, this);
               getServer().getPluginManager().registerEvents(listener1, this);
               getServer().getPluginManager().registerEvents(cpmain, this);

        }
    }

    Error
     

    Attached Files:

  2. This is the only needed line
     
  3. So like this?

    Code (Java):

    package me.artourious.compasslocator;

    import org.bukkit.event.Listener;
    import org.bukkit.plugin.java.JavaPlugin;

    public class Main extends JavaPlugin implements Listener{

           public void onEnable(){
           Listener listener = new Listener(this);
           getServer().getPluginManager().registerEvents(listener, this);
         
        }
    }
     

    Or like this?

    Code (Java):
    package me.artourious.compasslocator;

    import org.bukkit.event.Listener;
    import org.bukkit.plugin.java.JavaPlugin;

    public class Main extends JavaPlugin implements Listener{

           public void onEnable(){
           getServer().getPluginManager().registerEvents(this, this);
         
        }
    }
     
  4. Second one
     
    • Winner Winner x 1
  5. I mean, compared to the title it's out of topic but if it's not a really huge problem maybe we can solve it easily without flooding the forum with new 3-message threads.
     
  6. To elaborate a little on why you have this error. Listener is an Interface. What is an interface? It's a class that only contains Method signatures; so there is no logic behind it. If you tried to instantiate it using new; what would happen if you sent it a message? Well, Java wouldn't know, what to do with it. Therefore, you cannot instantiate it.
    What you can do is to have a class implement the interface (what you did there). By saying that, you are saying that this class contains all methods of the interface; and moreover that this class puts logic behind that. You can now instantiate the class, and the class can be of the type Listener.
    Once you will get a little more proficient in Java, you will see why this is a language construct, but for beginners, this usually makes no sense at all.
     
    • Informative Informative x 2