1

I have a Object say Car which has different methods to get Cars of different car makers e.g. Audi, BMW, Merc etc. All these car classes do not have any common interface or abstract classes on them but have some common properties as wheel, brakes etc. Car object has a method to identify which type of maker object should be used to extract properties. Can anyone suggest me a good approach to extract wheels from car object?

public class Car {
   public Audi getAudi() { return this.audi; }
   public BMW getBMW() { return this.bmw; }
   public Merc getMerc() { return this.merc; )

   public String getMaker() { return this.maker; }
}

public class Audi {
   public Wheel getWheel() { return this.wheel; }
   public Brakes getBrakes() { return this.brakes; }
}

public class BMW {
   public Wheel getWheel() { return this.wheel; }
   public Brakes getBrakes() { return this.brakes; }
}

public class Merc{
   public Wheel getWheel() { return this.wheel; }
   public Brakes getBrakes() { return this.brakes; }
}
skiwi
  • 66,971
  • 31
  • 131
  • 216
Atul
  • 11
  • 3
  • 2
    Add some code please, as it stands now *an option* is to use reflection, though I'd recommend to avoid it if possible. – skiwi Mar 06 '14 at 12:15
  • Well probably you are wanting to inspect (formally) unrelated classes. Check this thread: http://stackoverflow.com/questions/22200676/recursively-list-all-properties-exposed-by-a-class/22201894#22201894 – robermann Mar 06 '14 at 12:17
  • "All these car classes do not have any common interface or abstract classes on them" Why would anyone want to build a system that way??? – piet.t Mar 06 '14 at 12:18
  • 6
    Better give a **very good reason** as to why there is no interface here. – skiwi Mar 06 '14 at 12:26

1 Answers1

2

First of all, if all classes have the same (logical) methods, it does have an interface, just not a formal one, so your first task would be to implement a formal Interface which all classes must implement.

Alternatively you can use reflection to get all the methods and parse there names, but this method is cumbersome, and error prone (and horrible if your method signatures are too complex).

Alternatively, you can make your Car class abstract and have abstract methods for GetWheel() , GetBrakes() etc.

Also, it seems like you should use a Factory Pattern to hold your getAudi(), getBMW(), getMerc() methods. Which could either hold a Map of Car instances (if you're using single instances) or return new instances (which can be anonymous Inner classes instead of concrete classes), depending on what you're trying to achieve.

Mikkel Løkke
  • 3,710
  • 23
  • 37