0

So let's suppose that I have a class Animal in Java, and 3 child classes. The structure looks like this

class Animal{
  ...
  public breed(){
    //create a new child class object here
  }
}

class Bird extends Animal{
  ...
}

class Bear extends Animal{
  ...
}
class Frog extends Animal{
  ...
}

I want to create another object in breed class, but I want to create an object of the same child class, from which the method breed() was executed. For instance, if frog.breed() was executed I want to create a new Frog object there (assumming frog is a Frog object), if bear.breed() was executed I want to create a new bear object etc.

Is there any way to handle it in animal class, or I have to override method in every child class?

2 Answers 2

1

It's possible if you pass a reference to a function. I suspect method references and passing functions as arguments may be a bit beyond your level right now, but it's not that complicated.

class Animal {
  private final Supplier<Animal> ctor;

  Animal(Supplier<Animal> ctor) {
      this.ctor = ctor;
  }

  public Animal breed() {
    return ctor.get();
  }
}

class Bird extends Animal {
  public Bird() {
    super(Bird::new);
  }
}

The advantage of overriding is that Java allows to you make the return type more specific. So if you have a Bird bird; you could do Bird chick = bird.breed();.

class Bird extends Animal {
  public Bird breed() { //super return type is Animal, this return type is more specific
    return new Bird();
  }
}

Without overriding, you can't make the return type more specific, so you would have to assign it to a variable of type Animal chick = bird.breed(), unless you were to cast it.

Also achievable with reflection, but you should avoid it if possible.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes, you can do it, using reflection. But this approach isn't recommended, cause it's error-prone and you should consider rather using standard Java inheritance constructions. Example with recursion:

class Animal{

    public Animal breed() throws InstantiationException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        return this.getClass().getDeclaredConstructor().newInstance();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.