0

Now I'm having a bit of problem. I'm writing a converter functions and let's say I want to convert one type of card (one class) to another type (another class).

Let's say one is foo.bar.Card and the other is baz.banan.Card. I can have one

import foo.bar.Card;

but I can't do

import foo.bar.Card;
import baz.banan.Card;

as then the compiler can't tell them apart.

I could do just one of them and then prefix the other so I have Card and baz.banan.Card in my code, but I want to avoid having very long names. Ideally I would like to use bar.Card and banan.Card but is that possible and if so how?

liftarn
  • 429
  • 3
  • 21
  • the only way i could think of is wrapping one of them into a dummy class which is named different! – ParkerHalo Nov 06 '15 at 13:08
  • 1
    I think there is no way then. :( – Shivam Nov 06 '15 at 13:12
  • As mentioned in [this answer](http://stackoverflow.com/a/7193475/2773311) if you don't need to access `static` variables and functions you can extend one of them. – Arc676 Nov 06 '15 at 13:13

2 Answers2

4

You have 2 options:

  1. Rename your classes to unique names
  2. Refer to your class names using the fully qualified name:

    foo.bar.Card card = new foo.bar.Card();
    baz.banan.Card otherCard = new baz.banan.Card();
    

Another option, as whaleberg suggested, is to create a wrapper class with a different name.

Stefan
  • 1,433
  • 1
  • 19
  • 30
  • He explicitely said he doesn't want to prefix the Objects to avoid having very long names – ParkerHalo Nov 06 '15 at 13:10
  • 1. Not an option in my case. 2. That is what I don't want to do. – liftarn Nov 06 '15 at 13:10
  • Then there is no way to keep these classes apart. How should the compiler know that when you write `Card`, you mean package X and in the other case package Y if you don't provide the fully qualified name? Sometimes you want to avoid something but if the design doesn't allow it, your options are limited. – Stefan Nov 06 '15 at 13:11
  • 1
    A third option would be to wrap one of the classes in a new class that delegates to the wrapped class. – whaleberg Nov 06 '15 at 13:14
1

Unfortunately their isn't really a way to do this.

I do know of two somewhat useful workarounds:

Final Class

Create a wrapper class for one of the Card classes with the exact same methods that calls the Card objects methods. This isn't a very elegant approach unfortunately.

Mutable Class

Create a CardA class that extends Card and use CardA as your Card class.

Unfortunately these are you only two options. If these don't work you will have to use the fully qualified name.

Luke Melaia
  • 1,470
  • 14
  • 22