Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a base class object from a derived class

I have the following classes:

public class Base{

    //fields
    public String getStr(){
        String str = null;
        //Getting str from the fields
        return str;
    }
}

public class Derived extends Base{

    //fields
    //some other fileds
    public String getStr(){
        String str = null;
        //Getting str from the fields + some other fields
        return str;
    }
}

Now, I have a method which has a parameter of the type Derived.

public void makeStr(Derived d){
    Base b = null;
    //Getting the Base class subobject from d and printing the str
}

But I can't just do assignment like b = d; and then invoke b.getStr() because the method d.getStr() is going to be called.

How can I create the object of the type Base from the Base subobject of the objec of the type Derived? I fact, I just wanta create the copy of the Base subobject of the type Derived.

like image 203
St.Antario Avatar asked May 28 '15 08:05

St.Antario


People also ask

Can we create a base class object from derived class?

Answer: No. In general, When we create object of a class, its reference is stored in stack memory and object is stored in heap and address of object is assigned to class reference.

How do you create a base class object?

The derived class inherits the base class member variables and member methods. Therefore, the super class object should be created before the subclass is created. You can give instructions for superclass initialization in the member initialization list. Here you can see object is created for the inherited class.

Why would one create a base class object with reference to the derived class?

One reason for this could be that BaseClass is abstract (BaseClasses often are), you want a BaseClass and need a derived type to initiate an instance and the choice of which derived type should be meaningful to the type of implementation.


1 Answers

The whole point of overriding methods in sub-classes is that the method of the sub-class would get executed in run-time, even if the compile time type is that of the super-class.

If for some reason you require an instance of the super-class, you should add a copy constructor to your super-class and use it to create such an instance :

public class Base {
    ...
    Base (Base source) {
        // copy the properties from source
    }

}

Then :

public void makeStr(Derived d)
{ 
    Base b = new Base(d);
    ... b.getStr() will call the Base class implementation
}
like image 143
Eran Avatar answered Nov 01 '22 21:11

Eran