#Calculating fields that need to be passed into super()

1 messages · Page 1 of 1 (latest)

neat plaza
#

I'm not really sure how to ask this as i don't have the vocabulary down yet so forgive me while i muddle my way through.

I was playing with Inheritance trying to understand how extending classes work and I created a Parent class with a constructor that takes in 2 parameters

when i crated the child class i wanted to calculate a random level and generate the the name based on the level and passed into the super() but i couldn't do any calculations before calling the super()

i figured that i could make the two methods static and pass them in using a no method constructor and a private constructor that took in the two required parameters and calling the private constructor from the public one. this seems quite messy.

So my question is what would be the best practice/correct way to do this?

public class Item {
private String name;
private int level;

package items;

public class Item {
private String name;
private int level;

public Item(String name, int level) {
    this.name = name;
    this.level = level;
}

//getters and setters ommitted 

}

import java.util.Random;

public class HealthPotion extends Item{
private int quantity;
private int healingValue;
public HealthPotion() {
super()); //need to pass in name and level
int level = new Random().nextInt(3);
}

private String generateName(int level) {
    String potionName = "Health Potion";
    switch (level){
        case 0: 
            return "Lesser " + potionName;
        case 1:
            return "Great " + potionName;
        case 2:
            return "Greater " + potionName;
    }
    return potionName;
}

private void setHealingValue(int level){
    switch (level){
        case 0:
            healingValue = 100;
        case 1:
            healingValue = 200;
        case 2:
            healingValue = 300;
    }
}

}

jolly anvilBOT
#

<@&987246399047479336> please have a look, thanks.

pine abyss
#

Statements before super is something that will be possible in future Java versions, but not yet currently.

neat plaza
#

that will be awesome, but in the mean time what would be the correct way to handle this?

summer narwhal
#

only thing you can do is inline the computation into the super call:

super("some name", new Random().nextInt(3));

which isnt good but not much you can do at the moment
sometimes you would want to move complex computation to a method to make it more readable:

super("some name", generateRandom(3)); // isnt necessarily a complex computation, just an example