Alp
Alp

Reputation: 29739

Automatic casting from one object-class to another

I have two Java-Classes as follows:

public class MyClass {
...
}

public class MyClassList extends ArrayList<MyClass> {
...
}

Now i have any method which takes MyClassList as a parameter. The method should also accept MyClass instead. I know that I could overload the method.

Is there any possibility to achieve the same result with only one method? I am thinking of method in MyClass which automatically gets called and casts itself to MyClassList.

Upvotes: 0

Views: 307

Answers (2)

planetjones
planetjones

Reputation: 12633

But MyClassList does not extend MyClass.

Your method will have to take an Object type if, for some reason, you want a single method to accept both MyClass and MyClassList. Then you're going to have to do instanceof tests, if you want to work with their specific types (unless all you want do is call methods belonging to Object).

I think two separate methods is the best course of action here.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500155

No. You would have to overload the method. You can't provide user-defined implicit conversions in Java.

Upvotes: 3

Related Questions