Albazar
Albazar

Reputation: 53

Can a subclass be instantiated from an already instantiated superclass?

So I have a super class and I want to instantiate multiple sub classes off of it. The sub classes will probably be multi-threaded.
E.g.:

public class Person() {
    protected variables;
    public/private methods ect.
}

public class Man() extends Person {
    private variables;
    public/private methods;
}

public class Woman() extends Person {
    private variables;
    public/private methods;
}

I want to instantiate Person then extend Man and Woman classes off of it.
Like:

Person A = new Person();
Man B = //some how extends A;
Woman C = //some how extends A;

Or are there other ways of achieving the same goal?

Upvotes: 1

Views: 1088

Answers (2)

Ashley Frieze
Ashley Frieze

Reputation: 5458

You are misunderstanding the difference between a class and an object. A class is the overall definition of how an object will be composed. An object is a specific instance.

So if you create an instance of Person then that's just that a single object instance of the Person class. You can't extend it dynamically to have it as a Man at runtime (there are patterns where you could sort of do this, but not inheritance). If you want a Man you have create an instance of one.

Maybe your real question is different. Maybe you want to use an instance of Person as the template to create new instances of Man and Woman.

Imagine this

class Person {
     private String name;

     public Person(String name) { ... }
}

and a prototype person:

Person kelly = new Person ("Kelly");

Maybe you want to make a copy of the generic "kelly" as a Man and as a Woman - two separate objects, that happen to have this gender-neutral name in common

Man kellyMan = new Man(kelly);
Woman kellyWoman = new Woman(kelly);

What are we seeing above? We're seeing a copy constructor pattern. The contents of the original Person object could be copied into a new Man or Woman object which would then go on to live lives of their own. Example:

class Man : extends Person {
    public Man(Person template) { 
        super(template); // pass to superclass for copying
    }
}

class Person {
    ...
    public Person(Person template) {
        this.name = template.name;
        // etc
    }
}

This is not an uncommon way to go about things. Dynamically changing the type of objects at runtime is not common at all... I tried it once. Don't do it!

Upvotes: 2

peter
peter

Reputation: 78

If you want to inherit a class:

public class Child extends Parent { ...

You can have multiple child classes that inherit from the same parent, you just can't inherit from more than one class. Here are some examples of what you can use. Remember, when you write something like Person p = new Person(), you have p which is a reference to a Person object. Try messing around with mixing up object types with different references, and see what happens.

Upvotes: 0

Related Questions