How to declare an instance of a subclass correctly?

I am currently creating a text-based Java application for use in a test platform to try new things that I learn from this Java book that I am reading.

Now I am trying to declare an instance of a subclass (as the script script to find it). The parent class is Item and has two subclasses: Weapon and Armour .

However, no matter how I try to declare it, the IDE used (Eclipse) puts a line with the following error:

There is no instance of type Item available. You must assign the selection using an instance of the Item type (for example, x.new A (), where x is an instance of Item).

When I try to declare it as any of the following:

 Item machinePistol = new Weapon(); Weapon machinePistol = new Weapon(); Item machinePistol = new Item.Weapon(); Weapon machinePistol = new Item.Weapon(); 

For reference, the element class is as follows:

 package JavaAIO; public class Item { public String itemName; public double itemWeight; public class Weapon extends Item { public double damage; public double speed; } public class Armour extends Item { public double dmgResist; public double attSpdMod; } } 

So, if someone could tell me how I can create a weapon correctly (so that I can set the values โ€‹โ€‹of its fields and pass it to the player), I would really appreciate it.

+6
java instantiation subclass
source share
3 answers

"There is no instance instance of the Item type available. Must qualify the selection with an instance instance of the Item type (for example, xnew A (), where x is an instance of the Item) ."

This is pretty self-evident:

 Item machinePistol = new Item().new Weapon(); 

Or:

 Item item = new Item(); Item machinePistol = item.new Weapon(); 

However, I highly recommend putting them in your own classes so that you can:

 Item machinePistol = new Weapon(); 
+9
source share

For this:

 Item machinePistol = new Item(); Weapon machinePistol = new Item.Weapon(); 

you would like to declare your inner classes as static :

  public static class Weapon extends Item { public double damage; public double speed; } public static class Armour extends Item { public double dmgResist; public double attSpdMod; } 

Or another (and better) option is to not make them inner classes:

 public class Item {} public class Weapon extends Item {} public class Armour extends Item {} 

Then you can make them like this:

 Item machinePistol = new Item(); Item machinePistol = new Weapon(); Item someArmour = new Armour(); 
+5
source share

Weapon and Armour classes cannot be declared inside Item . Just declare them outside:

 public class Item { public String itemName; public double itemWeight; } public class Weapon extends Item { public double damage; public double speed; } public class Armour extends Item { public double dmgResist; public double attSpdMod; } 

So you can create them like this:

 Weapon machinePistol = new Weapon(); 
+1
source share

All Articles