当前位置: 代码迷 >> Eclipse >> 一个关于子类继承父类的有关问题,下初学者
  详细解决方案

一个关于子类继承父类的有关问题,下初学者

热度:104   发布时间:2016-04-23 13:49:20.0
一个关于子类继承父类的问题,求高手指教下菜鸟…
public class New {
public class Vehicle {
 
private String color;
private String kind;
private int speed;
 
Vehicle(){
color = "NULL";
kind = "NULL";
speed = 0;
}
 
public void setSpeed( int speed1){
speed = speed1;
}
 
public void setColor(String color1){
color = color1;
}
 
public void setKind(String kind1){
kind = kind1;
}
 
public int getSpeed(){
return speed;
}
 
public String getColor(){
return color;
}
 
public String getKind(){
return kind;
}
}
public class Car extends Vehicle{

private int passengerNumber; 

Car(){
super();
passengerNumber = 0;
};

public void setPassengerNumber(int passgerNumber){
this.passengerNumber = passengerNumber;
}

public int getPassengerNumber(){
return passengerNumber;
}
}
   
public static void main(String []args){
Car myCar = new Car();
  myCar.setColor("Black");
  myCar.setSpeed(200);
  myCar.setKind("Big");
  myCar.setPassengerNumber(4);
  System.out.println(" My Car :");
  System.out.println("Color: " + myCar.getColor());
  System.out.println("Speed: " + myCar.getSpeed());
  System.out.println("Kind : " + myCar.getKind() );
  System.out.println("The number of the passgers: "+ myCar.getPassengerNumber());
 
  }
}

  编译时报错为 MAIN方法中 Car myCar = new Car(); 有错,Exception in thread "main" java.lang.Error: Unresolved compilation problem: No enclosing instance of type New is accessible. Must qualify the allocation with an enclosing instance of type New (e.g. x.new A() where x is an instance of New).at New.main(New.java:57)

  自己猜想可能是子类继承父类时构造顺序引发的错误,具体还不清楚,求高手指点! 非常感谢!

------解决方案--------------------
探讨

你使用的是内部类,你把内部类看成是一个类的一个属性。那么在调用该属性的时候,你必须先new一个实例出来才能调用,所以把那段出错代码修改为如下就行了:Car myCar = new New().new Car();

------解决方案--------------------
楼主可以看看这篇博文
http://www.blogjava.net/raylong1982/archive/2007/10/24/155439.html
  相关解决方案