Home > database >  How to "refresh" the set-get of a class from one subclass of another class (Sorry for the
How to "refresh" the set-get of a class from one subclass of another class (Sorry for the

Time:11-09

I will try to explain as well as I can the problem I'm dealing with. SO I have a substract class "WeaponCarrier" in which I have a weapon.

  • That "Weapon" is a class that has a "void setHolder(WeaponCarrier holder){this.holder = holder}.
  • That "Weapon" class also has a "WeaponCarrier getHolder(){return holder;}" method.

What I'm trying to do is change the weapon setHolder/getHolder through a subclass in WeaponCarrier. Something like:

private class sword extends WeaponCarrier
{
   void methodName(){ weapon.setHolder(weapon.holder);} //This code doesn't work but I have tried a lot of things and nothing seemed to work either
}

The result I want is: When I "System.out.println(getHolder)" I want to get the new value from setHolder that I gave through the subclass.

I will take this question down if it doesn't make any sense to you. Thank you so much for your valuable time.

CodePudding user response:

This code does not work ...

If we look closely at this line ...

void methodName(){ weapon.setHolder(weapon.holder);}

... then we will see that it makes no sense, because the weapon object is setting a value on its field equal to its current value. It does not change anything ever.

If you change this line to something more useful, then you can do an override of a getter or a setter in the same way you would override any other method.

Ideally, you should cover your code by unit tests to ensure that it works exactly how you invisioned it.

CodePudding user response:

You could use an abstract class weapon and use an instance of that. Then use code like this

public abstract class Weapon{
    Weaponcarrier holder;
    String name;
    //this creates the name var for the weapon
    public Weapon(String name){
        this.name = name;
        //this sets the name that gets coded for the weapon to the instance of the weapon.
}
    public void setHolder(weaponCarrier){
        this.holder = weaponCarrier;
}
    public Weaponcarrier getHolder(){
        return this.holder
}
}

Then to make a sword(for example)

public class Sword extends Weapon{
public Sword(){
    super("Sword"/*the name*/);
}

now make a list where you add all Weapons to called weaponlist and add all weapons to that. Then make a function which returns the weapon's class when called. Then you can use that class to call the functions for that one instance. This is scalable to include all weapons that you want to use. if you don't understand the second part you can just ask and I will tell you the code for that.

Then you can enter the one you want to set it to between the brackets and it sets it to that. Also make sure you put the right new in because now it is setting itself to what it currently is

  •  Tags:  
  • java
  • Related