2

I am trying to write a simple program that should allow a user to save and display sets of heterogeneous, but somehow related data. For clarity sake, I will use a representative example of vehicles. The program flow is like this:

  1. The program creates a Garage object, which is basically a class that can contain a list of vehicles objects
  2. Then the users creates Vehicles objects, these Vehicles each have a property, lets say License Plate Nr. Once created, the Vehicle object get added to a list within the Garage object
  3. --Later on--, the user can specify that a given Vehicle object is in fact a Car object or a Truck object (thus giving access to some specific attributes such as Number of seats for the Car, or Cargo weight for the truck)

At first sight, this might look like an OOP textbook question involving a base class and inheritance, but the problem is more subtle because at the object creation time (and until the user decides to give more info), the computer doesn't know the exact Vehicle type.

Hence my question: how would you proceed to implement this program flow? Is OOP the way to go?

Just to give an initial answer, here is what I've came up until now. There is only one Vehicle class and the various properties/values are handled by the main program (not the class) through a dictionary. However, I'm pretty sure that there must be a more elegant solution (I'm developing using VB.net):

Public Class Garage
    Public GarageAdress As String
    Private _ListGarageVehicles As New List(Of Vehicles)

    Public Sub AddVehicle(Vehicle As Vehicles)
        _ListGarageVehicles.Add(Vehicle)
    End Sub
End Class

Public Class Vehicles
    Public LicensePlateNumber As String
    Public Enum VehicleTypes
        Generic = 0
        Car = 1
        Truck = 2
    End Enum
    Public VehicleType As VehicleTypes
    Public DictVehicleProperties As New Dictionary(Of String, String)
End Class

NOTE that in the example above the public/private modifiers do not necessarily reflect the original code

2
  • i suggest delegate pattern
    – Bryan Chen
    Commented Jun 10, 2013 at 23:01
  • Is there a reason you can't replace the object instance in the garage when you do learn the type? Commented Jun 10, 2013 at 23:10

4 Answers 4

6

No, there's no way to change the instantiated type of an object. A Vehicle is a Vehicle, and will remain such until it goes out of scope.

Your choices here are threefold:

  1. Make the type of Vehicle simply a property on the Vehicle object, and default it to Unknown.
    • This works best when there's little functional difference between a Car and a Truck.
    • Functions may return different results depending on the VehicleType, and you'll need to handle the Unknown case, but it's trivial to reassign.
  2. Replace the Vehicle with a new object of Car or Truck
    • This would require either a IsActuallyACar() method on the Vehicle which returns a Car, or a Car constructor which takes a Vehicle as an argument (which is the much better choice).
    • Going with this method requires you to manually remove the Vehicle from everywhere that it's stored, and replace it with the newly created object.
  3. Rethink your design so that Vehicle is abstract and you don't create the object until you know what type it is.
    • This is probably the best option from an OO perspective.
    • You may need to temporarily store data in a non-Vehicle structure as you gather it, but you don't need to worry about changing the type later.

In your described scenario, I suspect #1 is the best choice. Simply have logic which says "If the object has its type set to Car, then show this, if it's set to Truck show this." It's not great OOP design, but it handles the "Vehicle of unknown type" the best.

2
  • 2
    Good answer. I just wanted to point out that the reason you can't change the type is that storage is allocated based on the original type, so there may not be space available for any extra fields of the subclass. Commented Jun 11, 2013 at 2:51
  • Using a VehicleType property vice sub-classing has the benefit of preventing a potential explosion of subtypes. And thumbs-up on using an enum for the types, Federico.
    – radarbob
    Commented Jun 11, 2013 at 15:28
1

No, you can't change the class of an object once instantiated, at least not in any programming language I know of. The reason is that this would blow up all sorts of guarantees a class hierarchy would otherwise give you; not to mention that "changing the class of an object" is a highly undefined requirement - how do you migrate the object's state? How do you map fields from one class to the other?

Considering your problem at hand; you have fallen prey to the seduction of naive polymorphism and reuse-by-inheritance. While both a Car and a Truck are vehicles, it is not very wise to have them inherit from Vehicle directly and encode all the behavior in these three classes. In other news, the textbook is wrong.

Instead, split the functionality into components. A Vehicle has a license plate, and a type. The type determines whether it is a car or a truck. You can then swap out the vehicle's type without changing its base properties.

Also, note that you are probably lying about your data. You create a Vehicle object without actually having a vehicle at hand; all you want is store the license plate number. So maybe putting the license plate into its own class, and linking it to an actual vehicle later might be a better design choice.

8
  • Python allows changing an object's type at runtime, although it's more a side-effect of the implementation than an actual, intended language feature. Commented Jun 11, 2013 at 8:49
  • Well, Python's classes are very loose anyway; you can monkey-patch methods and fields into existing objects, too, so the class doesn't really mean a lot. Changing the class is an intended feature in the sense that the intention is that you can change anything you bloody damn choose to.
    – tdammers
    Commented Jun 11, 2013 at 8:53
  • CLOS does it too. And I disagree when you say that classes do not mean a lot if they can be changed at runtime.
    – coredump
    Commented Jun 11, 2013 at 9:42
  • 1
    @coredump: What I mean is that when an object can be monkey-patched, knowing what its class is doesn't give you any guarantees about the object itself, other than the constructor that was used to set up the object's initial state. In something like Java, knowing an object's class tells you which fields and methods it has, and which interfaces it implements. You can't do that in Python.
    – tdammers
    Commented Jun 11, 2013 at 10:04
  • @tdammers: in practice, you have an idea of which class may or may not change dynamically and you can still access the information reliably at runtime; this is something you can do also in Java with class loaders and introspection. I agree you don't have static types but this is not necessarly a drawback.
    – coredump
    Commented Jun 11, 2013 at 10:31
0

I would use a different design where garage contains a list of parkingspace objects. The parkingspace object would implement the interface Licensplate.

Now I would have the vehicle object also implement the licensplate interface.

That way you can instantiate your list of parkingspaces, with corrensponding licenseplate numbers and instantiate your cars and trucks later with licensplates.

0

probably you are looking for this pattern

you have to tweak this code to your exact requirement.

public interface IVehicle
{  
    string VehicleType{get;}
    int NumberOfSeets{set;get;}
    int Corgosize{set;get;}
}

public class Car:IVehicle
{
    private int _numseets;
    private int _corgo;
    public string VehicleType{
        get{return "CAR";}
    }

    public int NumberOfSeets
    { 
       get{return _numseets;}
       set{_numseets = value;}
    }

    public int Corgosize
    {
        get { return _corgo; }
        set { _corgo = value; }
    }
}

public class Truck : IVehicle
{
    private int _numseets;
    private int _corgo;
    public string VehicleType
    {
        get { return "Truck"; }
    }

    public int NumberOfSeets
    {
        get { return _numseets; }
        set { _numseets = value; }
    }

    public int Corgosize
    {
        get { return _corgo; }
        set { _corgo = value; }
    }
}

public class Vehicle : IVehicle
{
    private IVehicle _vehicle;
    public Vehicle(IVehicle refVehicle)
    {
        _vehicle = refVehicle;
    }
    public string VehicleType
    {
        get { return _vehicle.VehicleType; }
    }

    public int NumberOfSeets
    {
        get { return _vehicle.NumberOfSeets; }
        set {  }
    }

    public int Corgosize
    {
        get { return _vehicle.Corgosize; }
        set {  }
    }

}

public class MainClass
{
    public static void Main()
    {
        Vehicle car, truck;
        car = new Vehicle(new Car());
        truck = new Vehicle(new Truck());
        Console.WriteLine("Car type ->{0}",car.VehicleType);
        Console.WriteLine("truck type ->{0}", truck.VehicleType);
        Console.ReadKey();

    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.