package com.yidao;public class InheritTest {
private String name(Ancestor ancestor) {
return ancestor.getAncestorName();
} public static void main(String[] args) {
Descendant descendant = new Descendant();
descendant.setFamilyName("descendant");
System.out.println(new InheritTest().name(descendant));
}
}class Ancestor {
private String familyName; /**
* @return the familyName
*/
public String getAncestorName() {
return familyName;
} /**
* @param familyName the familyName to set
*/
public void setfamilyName(String familyName) {
this.familyName = familyName;
}
}
class Descendant extends Ancestor{
private String familyName;
private String middleName;
/**
* @return the familyName
*/
public String getFamilyName() {
return familyName;
}
/**
* @param familyName the familyName to set
*/
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
/**
* @return the middleName
*/
public String getMiddleName() {
return middleName;
}
/**
* @param middleName the middleName to set
*/
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
}
为什么输出结果是null?
descendant.setFamilyName("descendant");这句话不是已经改变了familyName的值吗?
而且我debug的时候familyName居然有两个值,一个是Descendant 的值("descendant "),一个是Ancestor的值(null)。
这就不懂了。Descendant不是把Ancestor的familyName继承过来了吗?
强淫帮帮我啊。
this.familyName = familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}两个名字都不一样,不是覆盖
在子类中尼故意写了个setFamilyName方法吗?
package com.yidao;public class KKK { public static void main(String[] args) {
B b = new B();
b.setTest("b");
System.out.println(b.result());
System.out.println(b.getTest());
}
}class A {
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
public String result() {
return "A.Test=" + this.test;
}
}class B extends A {
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
输出结果:
A.Test=null
b
是继承了方法,和属性,而没有继承对象地址.另外由于没有重写 result方法,所以,a.Test为null,就这样子.好像儿子有100块,父亲手里就要有100块?不合理吧