Asperger
Asperger

Reputation: 3222

Create child class from instantiated base class?

I know this sounds weird but is it possible to create a child class that inherits from an already instantiated base class? I know I can use DI but im just wondering.

Edit: I know this is more a feature of prototype based languages such as javascript. Either way im wondering if this is even worth considering if something like this is possible.

Lets assume I have the following:

public class Parent {
  protected id;

  public Base(int id) {
    this.id = id;
  }
}

public class Child extends Parent {
  public void getID() {
    return id;
  }
}

So then in my main I would do something like this:

Parent x = new Parent(1900);
// How to make a child of this particular base?
// x child = new Child();

Upvotes: 0

Views: 37

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074198

How to make a child of this particular base?

You can't. The closest you can come is if Parent implements a copy constructor and Child uses it in a constructor, which would let you create a Child that copied that particular parent's state...

...which isn't really all that close. As you say, what you're looking for there is prototypical inheritance, which Java just doesn't have.

Upvotes: 1

Related Questions