Note that there are some explanatory texts on larger screens.

plurals
  1. POJava - How to properly use Extends/Implements
    primarykey
    data
    text
    <p>Okay so I am kind of confused about the uses of "extends" and "implements". Let me give a scenario, let's say I am making a simple tower defense game. So it was my understanding that if I made a class (TowerBase.java), I can fill it with variables and methods, such as; int hp, int damage, int attack(){ ... }, etc.... I figured I could then make many types of towers, lets say one is an archer tower, and inside TowerArcher.java I want to set TowerBase's variables to unique values for said tower. My understanding was that inside of TowerArcher if I extend TowerBase I have access to all of TowerBase's variables and methods since TowerBase is now the parent. So I tried this:</p> <pre><code>public class TowerBase { //Health (Range: 1-100) int hp; public int attack(int blah){ //Blah blah how the tower goes about attacking foe } </code></pre> <p>Then in the TowerArcher.java</p> <pre><code>public class TowerArcher extends TowerBase{ //Set TowerArcher's unique values hp = 10; } </code></pre> <p>Now somewhere in the game...</p> <pre><code>TowerArcher archer; archer.attack(blah); </code></pre> <p>Eclipse throws this syntax error in TowerArcher.java at "hp = 10;": VarableDeclaratorId expected after this token. Which I presume that it was saying it doesn't know what hp is. This confuses me since I thought it would know what hp was since it's in the parent class. I have found work-arounds but they don't seem as effective and even if they work they still leave me confused as to what extends and implements are really for. Basically what I am trying to find out here is; <br/> 1: What does extends do <br/> 2: How could I use extends in my program intuitively <br/> 3: What does implements do <br/> 4: How could I use implements in my program intuitively <br/> 5: What I should use in this scenario where I have many different objects (towers) doing nearly the same thing, perhaps TowerArcher TowerBunker TowerSnipernest TowerBarricade etc. <br/> <br/> I know I am asking for a lot but I couldn't find a good post on it so this could help others too :) <br/>P.S. If I am missing any needed information please let me know. I am so clueless at this point.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload