父类可以接收子类的实例,方法的覆盖,属性的隐藏,这些都使我非常疑惑,今天有点时间记录之。
话不多说,直接上代码上结果
1.
public class TestDto{
public static void main(String[] args) {
ClassInitializeChild child=new ClassInitializeChild();
System.out.println(child.name);
}
}
class ClassInitializeParent{
public String name="parent";
public void print(){
System.out.println("parent="+name);
}
public ClassInitializeParent(){
print();
}
}
class ClassInitializeChild extends ClassInitializeParent{
public String name="child";
public void print(){
System.out.println("child="+name);
}
public ClassInitializeChild(){
print();
}
}
结果:
child=null
child=child
child
2.
public class TestDto{
public static void main(String[] args) {
ClassInitializeParent parent=new ClassInitializeChild();
System.out.println(parent.name);
}
}
class ClassInitializeParent{
public String name="parent";
public void print(){
System.out.println("parent="+name);
}
public ClassInitializeParent(){
print();
}
}
class ClassInitializeChild extends ClassInitializeParent{
public String name="child";
public void print(){
System.out.println("child="+name);
}
public ClassInitializeChild(){
print();
}
}
结果:
child=null
child=child
parent
3.
public class TestDto{
public static void main(String[] args) {
ClassInitializeParent parent=new ClassInitializeChild();
parent.print();
}
}
class ClassInitializeParent{
public String name="parent";
public void print(){
System.out.println("parent="+name);
}
}
class ClassInitializeChild extends ClassInitializeParent{
public String name="child";
public void print(){
System.out.println("child="+name);
}
}
结果:
child=child
4.
public class TestDto{
public static void main(String[] args) {
ClassInitializeParent parent=new ClassInitializeParent();
parent.print();
}
}
class ClassInitializeParent{
public String name="parent";
public void print(){
System.out.println("parent="+name);
}
}
class ClassInitializeChild extends ClassInitializeParent{
public String name="child";
public void print(){
System.out.println("child="+name);
}
}
结果:
parent=parent