Let's say I have something like: Vehicles.
Below Vehicles I have Cars, Trucks and Pickups.
Below Cars I only have BMW and Toyota.
Now I want to call something like:
if (NumberOfSeats(Vehicles.Cars.Toyota) {}
So NumberOfSeats should be restricted to only receive BMW and Toyota:
public int NumberOfSeats(??) { return 4;}
But it should give a compile time error if I call:
if (NumberOfSeats(Vehicles.Cars.Yamaha) {}
Furthermore I would like to have a method to BMW, that will return a string value (let'say Name()
)
Should my class composition be looking at Enums, Classes, Inheritance or combination?
I guess you are thinking in backwards. My way of thinking is to create analogy between real-world objects and software classes (This is my way oıf Object Oriented thinking).
When I consider a real-world scenario there is no such thing as "number of seats" in the world itself. It is a property of a vehicle. Cars have this property buses have this property, Cars usually have 4 (or 5) seats, buses have 45 etc.
So I would implement it as a property of a vehicle ot a self method. This way it will be more meaningful. Such as:
public interface IVehicle
{
int NumberOfSeats { get; }
string Brand { get; set; }
}
public class Car : IVehicle
{
public int NumberOfSeats { get; private set; }
public string Brand { get; set; }
public Car(int noofseats, string brand)
{
this.NumberOfSeats = noofseats;
this.Brand = brand;
}
}
Car bmw = new Car(4, "BMW");
Car toyota = new Car(4, "Toyota");
Car qashqai = new Var(7, "Nissan");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.