如何在java中获取超类的实例?

如何在java中获取超类的实例?,java,polymorphism,Java,Polymorphism,让我解释一下我的情况: public class Car extends Vehicle{ public Car() { } public Car(String model){ super(model); AutoParts autoParts=new AutoParts(Car.this.getSuperClass); //get compile error here } } public class Au

让我解释一下我的情况:

 public class Car extends Vehicle{
      public Car() { }
      public Car(String model){
        super(model);
        AutoParts autoParts=new AutoParts(Car.this.getSuperClass); //get compile error here
      }
    }


   public class AutoParts{
     Vehicle _Vehicle;
     public AutoParts() { }
     public AutoParts(Vehile vehicle){
        this._Vehicle=vehicle;
     }
   }
对不起,这个可怕的例子。但是在初始化过程中,
Ford=newford(Car.this.getSuperClass),我希望能够将超类的实例作为参数传递给构造函数

我该怎么做?如何获取超类的实例

**

编辑:
类名,
Ford
重命名为
AutoParts

我不确定下面的操作方法是否正确,但我调整了您想要做的

public class Vehicle{
    private String model;

    public Vehicle() {
    }

    public Vehicle(String model) {
        this.model = model;
    }

    public String getModel() {
        return model;
    }
}

public class Car extends Vehicle {

    public Car() {
    }

    public Car(String model) {
        super(model);
        AutoParts autoParts = new AutoParts((Vehicle)this); //Cast the instance of this class to it's superclass and pass the instance to the constructor of the autoParts object
        System.out.println(autoParts.getVehicle().getModel());
    }
}

public class AutoParts {

    Vehicle vehicle;

    public AutoParts() {
    }

    public AutoParts(Vehicle vehicle) {
        this.vehicle = vehicle;
    }

    public Vehicle getVehicle() {
        return vehicle;
    }
}
现在,以下用法将起作用:

Car car = new Car("Model T");
// Output prints in the car constructor: Model T

第一个问题是为什么特别需要超类的实例?我假设你不想让你的福特车接触到汽车的额外成员(扩展了汽车等级),因为福特车可能是,比如说,卡车。您可以像这样使用铸造来实现这一点:

Ford ford=new Ford((Vehicle)this);
但是,如果您的汽车中有任何方法覆盖(即“this”对象),这些方法覆盖将仍然存在于您传递给Ford构造器的车辆中,这是您想要的吗


我认为我们已经脱离了面向对象设计的老路,而不是光顾别人。福特没有汽车,因此拥有汽车领域是错误的。福特是一辆汽车,因此它应该扩展汽车。还有,为什么在创造一辆汽车时,它一定要创造一辆福特?汽车是福特汽车,因此我会让汽车类扩展到福特汽车(Jon Skeet,不是相反,因为可能会有福特卡车/摩托车等)

试试全新的
福特(this)
Car
的每一个实例也是
Vehicle
的一个实例,不需要磨磨蹭蹭地自省。但是,请注意,在某些IDE中这可能会给您一个警告(这是理所当然的),您在任何地方都没有超类的实例。你有一个班级推荐信,但我不明白你为什么要这么做你为什么要这么做?只需传递一个
汽车
的实例,然后在
福特
中,将其用作
汽车
中的一个。子类的实例可以用作超类的实例在设计方面,为什么
Ford
会组成
Vehicle
?我希望
Ford
成为
Car
的一个子类,@gefei:Ford f=new Ford(新车(“蒙迪欧”);会有用的。