如何在java中获取SuperClass的实例? [英] How to get an instance of SuperClass in java?

查看:46
本文介绍了如何在java中获取SuperClass的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我解释一下我的情况:

Let me explain my situation:

 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);,我希望能够将超类的实例作为参数传递给构造函数.

Sorry for the horrible example. But during the initialization, Ford ford=new Ford(Car.this.getSuperClass);, I want to be able to pass an instance of the superclass as a parameter to the constructor.

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

How do I do it? How do I get the instance of a superclass?

**

类名,Ford 更名为AutoParts

推荐答案

第一个问题是你为什么要特别想要一个超类的实例?我假设您不希望您的 Ford 访问 Car 的其他成员(扩展 Vehicle 类),因为 Ford 可能是一辆卡车.您可以像这样使用强制转换来实现此目的:

The first question is why do you want an instance of the superclass specifically? I shall assume that you do not want your Ford to have access to a Car's additional members (that extend the Vehicle class), because a Ford may be, say, a truck. You can use casting like so to achieve this:

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

但是,如果您的 Car 中有任何方法覆盖(即this"对象),这些方法仍将保留在您传递给 Ford 构造函数的 Vehicle 中,这是您想要的吗?

However, if you have any method overrides in your Car (that is, the "this" object) these will still be in place in the Vehicle that you pass to your Ford constructor, is that what you want?

在没有光顾的情况下,我认为我们在这里偏离了面向对象设计的常规.福特没有 Vehicle,所以有一个 Vehicle 字段是错误的.福特是一种车辆,因此它应该扩展车辆.还有为什么在创造汽车时,它一定会创造福特吗?汽车是福特,所以我会让汽车类扩展福特(而不是相反,乔恩斯基特,因为可能有福特卡车/摩托车等)

Without being patronising, I think we're off the beaten track of OO design here. A Ford doesn't have a Vehicle, so having a Vehicle field is wrong. A Ford IS a vehicle, so therefore it should extend Vehicle. Also how come when creating a Car, does it necessarily create a Ford? A car IS a Ford, so I would have the Car class extend Ford (not the other way round, Jon Skeet, as there could be Ford trucks/motorbikes etc.)

这篇关于如何在java中获取SuperClass的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆