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继承过来了吗?
强淫帮帮我啊。

解决方案 »

  1.   

    Ancestor中的familyName和Descendant中的familyName是2个不同的变量,父类的私有变量是可以继承,但是不能在子类里面直接修改,比如在你整个例子中也只能通过getAncestorName和setfamilyName对父类的familyName进行操作
      

  2.   

        public void setfamilyName(String familyName) {
            this.familyName = familyName;
        }
     public void setFamilyName(String familyName) {
            this.familyName = familyName;
        }两个名字都不一样,不是覆盖
      

  3.   

    Ancestor中的familyName和Descendant中的familyName是2个不同的变量,你只改变了Descendant中的familyName值,而后你的打印是将对象向上转型到了Ancestor,输出Ancestor中的familyName当然为null,建议你去看看父类和子类的内存分配情况
      

  4.   

    setfamilyName,
    在子类中尼故意写了个setFamilyName方法吗?
      

  5.   


    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
      

  6.   


    是继承了方法,和属性,而没有继承对象地址.另外由于没有重写 result方法,所以,a.Test为null,就这样子.好像儿子有100块,父亲手里就要有100块?不合理吧