51Testing软件测试论坛

标题: 子类直接创建对象和父类的引用指向子类的对象有什么区别? [打印本页]

作者: 小小哒    时间: 2019-1-8 11:47
标题: 子类直接创建对象和父类的引用指向子类的对象有什么区别?
以下一块代码我子类直接创建对象和父类的引用指向子类的对象运行结果是一样的,平常做一些练习的时候也发现这两者运行结果都是一样,子类直接创建对象和父类的引用指向子类的对象有什么区别?除了概念上的多态

public class Test10 {
public static void main(String[] args) {
  A1 a1=new A1(1);
  a1.show();
  System.out.println("a1.x="+a1.x);
  A12 a12 =new A12(10,20);
  a12.show();
  System.out.println("a12.x="+a12.x);
  A1 c =new A12(10,20);
  c.show();
  System.out.println("c.x="+c.x);
  
}
}
class A1{
int x;
A1(int x){
  this.x=x;
}
void show(){
  System.out.println("a1.x="+x);
}
}
class A12 extends A1{
A12(int x,int y){
  super(x);
  this.x=y;  
}
void show(){
  System.out.println("super.x="+super.x+" this.x="+this.x);
}
}


在学课程:
零基础学编程JAVA语言直通班
http://www.atstudy.com/course/1006


作者: 学掌门网校    时间: 2019-1-8 11:51
仅仅是这个代码,确实就是多态的区别。多态是个非常重要的基本特性,几乎所有的设计模式都依赖于此。

另外,如果父子类的show方法是static void show()的话,你就能看到不同了。






欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2