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
.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With