读书人

不同类的对象中具有相同名字的方法,怎

发布时间: 2011-12-26 23:09:59 作者: rapoo

不同类的对象中具有相同名字的方法,如何调用可以节省代码?
已经有类A和类B,而且其中有几个名字相同成员变量以及get,set的方法,如其中的test的及其get\set方法;

问题是,在另外的一个类中,如何用同一段代码调用这不同对象中的名字相同的方法?

值得注意的是,下面的代码只是打个比方,而实际中,这两个类中有很多名字相同的方法,而且都要在Test中调用,怎么可以节省代码?

public class A {
private int a = 0;

private String test = "a ";

public int getA() {
return a;
}

public void setA(int a) {
this.a = a;
}

public String getTest() {
return test;
}

public void setTest(String test) {
this.test = test;
}
}

public class B {

private int b = 0;

private String test = "b ";

public int getB() {
return b;
}

public void setB(int b) {
this.b = b;
}

public String getTest() {
return test;
}

public void setTest(String test) {
this.test = test;
}
}


public class Test {

public static void main(String[] args) {

Object obj = null;
// 怎么样写可以直接调用这些名字相同的方法?
System.out.println(obj.getTest());
}
}

[解决办法]
那你这些方法为什么不写在父类之中,再由 A 和 B 来继承呢?

读书人网 >J2SE开发

热点推荐