//父类
public class Father {
static String MSG="i am father";
String getword(){
return MSG+":你说呢";
}
}
//子类
public class Son extends Father{
static String MSG="i am Son";
}
//
public static void main(String[] args) throws IOException {
Son son = new Son();
String getword = son.getword();
System.out.println("getword = " + getword);
}
怎么样能让他输出 i am son:你说呢
我只能想到这个:把成员变量都放在map,然后根据名字取对应的成员变量 如map.get(son).get(msg)
/**
* @author huazie
* @version 2.0.0
* @since 2.0.0
*/
public class Test {
public static void main(String[] args) {
Son son = new Son();
String getword = son.getword();
System.out.println("getword = " + getword);
}
}
//父类
class Father {
String MSG="i am father";
String getword(){
return getMsg()+":你说呢";
}
String getMsg() {
return MSG;
}
}
//子类
class Son extends Father{
String MSG="i am Son";
@Override
String getMsg() {
return MSG;
}
}
使用继承的父类方法时,想使用子类的成员变量来输出特定信息,可以考虑使用map。下面给出具体的解决方案:
1.在子类中定义一个map,key存储父类方法需要的变量,value存储子类的成员变量。
2.在调用父类方法时,使用call或apply方法改变回调函数内部的this,将map作为参数传入。
3.在父类方法内部使用传入的map参数,通过key获取到对应的子类成员变量,进行实现。
代码实现示例:
class Parent {
saySomething(str) {
console.log(`i am parent: ${str}`);
}
}
class Son extends Parent {
constructor(name) {
super();
this.name = name;
this.map = new Map();
this.map.set('saySomething', 'i am son');
}
saySomething(str) {
this.map.set('saySomething', `i am son: ${str}`);
super.saySomething.call(this, this.map);
}
}
const son = new Son('Mike');
son.saySomething('你说呢');
输出结果为:i am son: 你说呢
上述代码中,子类Son中定义了一个map,key为调用父类方法需要的变量,value为子类的成员变量。在Son的saySomething方法中,将子类的成员变量存储到map中,并使用call方法改变回调函数this的指向,将map作为参数传入。在父类的saySomething方法内部,通过map的key获取到对应的子类成员变量,进行输出。
这种方法相对来说比较简单,易于理解。如果map的数量很大,可以考虑使用其他的数据结构来实现。同时需要注意,如果子类重新定义了父类方法,需要在子类方法中调用super来实现继承。