日期:2014-05-20  浏览次数:20804 次

关于多态的问题
现有如下代码:
public   class   A   {
private   int   x,y;
private   int   a,b;

public   A(){
System.out.println( "A   Constructor1 ");
}

public   A(int   x,int   y){
System.out.println( "A   Constructor2 ");
this.x=x;
this.y=y;
}

public   void   returnType(){
System.out.println( "This   is   A ");
}

public   void   setValue(int   a,int   b){
this.a=a;
this.b=b;
}

public   void   display(){
System.out.print( "A   display: ");
System.out.println( "x= "+x+ "   "+ "y= "+y);
System.out.println( "a= "+a+ "   "+ "b= "+b);
}
}

public   class   B   extends   A   {
private   int   x,y;
private   int   c,d;

public   B(){
System.out.println( "B   Constructor1 ");
}

//显示B中(包括从A中继承的)所有的域
public   B(int   x,int   y){
super(x,y);//调用A的构造器
System.out.println( "B   Constructor2 ");
this.x=x;
this.y=y;
}

public   void   setValue(int   c,int   d){
this.c=c;
this.d=d;
}

public   void   display(){  
super.display();
System.out.print( "B   display: ");
System.out.println( "x= "+x+ "   "+ "y= "+y);
System.out.println( "c= "+c+ "   "+ "d= "+d);
}
}

public   class   Test   {

/**
  *   @param   args
  */
public   static   void   main(String[]   args)   {
B   []b=new   B[10];
A   []a=b;
a[0].display();     //该行语句发生异常
}
}

运行后,为什么会产生如下的异常:
Exception   in   thread   "main "   java.lang.NullPointerException
at   Test.main(Test.java:29)
注:也就是a[0].display();这句发生异常。


请问是不是元素是对象的数组变量没有多态性?



------解决方案--------------------
class A { //首先你的问题在这里,一个文件里面只能有一个类是public的(当然内部类可以 是),下面的B类也是一样的问题
private int x,y;
private int a,b;

public A(){
System.out.println( "A Constructor1 ");
}

public A(int x,int y){
System.out.println( "A Constructor2 ");
this.x=x;
this.y=y;
}

public void returnType(){
System.out.println( "This is A ");
}

public void setValue(int a,int b){
this.a=a;
this.b=b;
}

public void display(){
System.out.print( "A display: ");
System.out.println( "x= "+x+ " "+ "y= "+y);
System.out.println( "a= "+a+ " "+ "b= "+b);
}
}

class B extends A {
private int x,y;
private int c,d;

public B(){
System.out.println( "B Constructor1 ");
}

//显示B中(包括从A中继承的)所有的域
public B(int x,int y){
super(x,y);//调用A的构造器
System.out.println( "B Constructor2 ");
this.x=x;
this.y=y;
}

public void setValue(int c,int d){
this.c=c;
this.d=d;
}

public void display(){
super.display();
System.out.print( "B display: ");