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.


Source: java

Leave a Reply