如何在java中获取SuperClass的实例?

时间:2016-05-01 06:52:06

标签: 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 AutoParts{
     Vehicle _Vehicle;
     public AutoParts() { }
     public AutoParts(Vehile vehicle){
        this._Vehicle=vehicle;
     }
   }

抱歉这个可怕的例子。但是在初始化期间Ford ford=new Ford(Car.this.getSuperClass);,我希望能够将超类的实例作为参数传递给构造函数。

我该怎么办?我如何获得超类的实例?

**

编辑:

班级名称,Ford已重命名为AutoParts

2 个答案:

答案 0 :(得分:3)

第一个问题是你为什么要特别想要一个超类的实例?我将假设您不希望您的福特能够访问汽车的其他成员(延长车辆类别),因为福特可能是卡车。你可以像这样使用cast来实现这个目标:

Ford ford=new Ford((Vehicle)this);

但是,如果您的Car中有任何方法覆盖(即"此"对象),那么这些仍会在您传递给Ford构造函数的Vehicle中就位,那就是你的意思要什么?

在没有光顾的情况下,我认为我们已经脱离了OO设计的局面。福特没有车辆,因此拥有车辆领域是错误的。福特是一种车辆,因此它应该扩展车辆。创造汽车怎么样,它是否必然会创造一辆福特?一辆汽车是福特汽车,所以我会让汽车级扩展福特(不是相反,Jon Skeet,因为可能有福特卡车/摩托车等)。

答案 1 :(得分:1)

我不确定以下是OP的正确方法,但我会调整你想做的事情

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