Home > other >  How can i access a subclass variable from superclass
How can i access a subclass variable from superclass

Time:03-31

My subclass is Player and I need to use fields money and name in my superclass Pistol. I know how can I use superclass variables in subclasses but I have to learn how can I do the reverse? Thank you.

public  class Player extends Pistol {
   int money;
   String name;
   Player borrower;
   Player target;

   int amount;
   boolean terrorist;
   int health;
   //CONSTRUCTOR
   public Player(){}

   public Player(String name,boolean terrorist, int money,int health){
    this.name=name;
    this.terrorist=terrorist;
    this.money=money;
    this.health=health;
   }
}


public class Pistol {
    int bullets = 20 ;

    public Pistol(){
    
    }
    
    //LOAD MAGAZINE METHOD
    public  void getBullet(){
        
        if((20-bullets)*5 <= money && bullets!=20){
            money=money-(20-bullets)*5;
            bullets=20;
            System.out.println("Success! The real war begins now!");
            System.out.println("INFO : "  name  " has 20 bullets in his/her pistol");
            System.out.println("INFO : "  name  " has "  money  "$");
        }
        else{
            System.out.println("Player can not afford it now.");

        }
    }
}

CodePudding user response:

You can't. A subclass extends a superclass, because you tell the subclass to extend the superclass, the subclass knows which class the parent is. The parent doesn't know any thing from its children.

CodePudding user response:

A parent can't have access to his subclasses variables. It's not declared in the same context so the parent has no idea what the variable itself is.

The real problem with your code is that a class extends another when they share variables, yes, but they need to have a real logical connection between them, for example :

    public class Animal {
    ...
    }
public class Cow extends Animal {
    ...
    }
public class Chicken extends Animal {
    ...
    }

Or :

public class TransportationDevice {
    ...
    }
public class Plane extends TransportationDevice {
    ...
    }
public class Car extends TransportationDevice {
    ...
    }

In the two examples above, the children have a logical connection with their respective parents.

In your case, a Person has no connection with a pistol. You should re-work the structure of your code without having a parent/children relation between those to classes.

I would personally have 3 classes : Player Pistol Bullet

Your player could receive an Object pistol and a list of bullets (mag) and load his mag

  • Related