【发布时间】:2015-08-10 15:31:57
【问题描述】:
我有以下课程:
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;
}
}
现在,我有一个方法,它的参数类型为Derived。
public void makeStr(Derived d){
Base b = null;
//Getting the Base class subobject from d and printing the str
}
但我不能像b = d; 那样做赋值然后调用b.getStr(),因为方法d.getStr() 将被调用。
如何从Derived 类型的对象的Base 子对象创建Base 类型的对象?事实上,我只想创建 Derived 类型的 Base 子对象的副本。
【问题讨论】:
-
str不是字段,而是方法变量。 -
@amit 还有?我们从字段中创建 str 。我认为创建该字符串的细节(例如在字段上调用 toString() 方法)在这里并不重要。
-
我误解了您的意图,虽然您将
str称为字段本身 -
这是
DerivedextendsBase还是您的代码原样? -
@dubey-theHarcourtians 当然,是的。已更新。
标签: java class inheritance