Pergunta

how can I make class X extends class Y in a particular condition? like I have a Super class Person and have an attribute age, another class called Adult, class Adult extends Person if the age is between 12 and 20? If it is not possible, do you have alternatives?

Foi útil?

Solução

I have tried to implement what you are asking with HAS-A relationship and runtime polymorphism.

In below example, Age is a parent class containing more generalized properties for all age groups.

Different age groups are divided in several class. Those classes contains age specific code or properties and will extend Age class. For example Young and Elder class.

class Age {
    // Generalized code for Age class
}

class Young extends Age {
    // more specific code of Young class
}

class Elder extends Age {
    // Elder class specific code
}

public class test {
    Age age ; 
    int ageValue ;

    public Age returnVal(int ageValue){
        if (ageValue < 20) {
            age = new Young();
        } else { 
            age = new Elder();
        }

        // age object you get will be according to ageValue.
        return age;
    }
}

returnVal() method will return you the object of either Young class or Elderclass according to ageValue.

Outras dicas

You might define a Person class with a .isAdult() instance method that returns a boolean, true if and only if the Person instance has age at least 12. This seems simpler to me at least.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top