Java – Cast an Object into a class

classeclipsejavasubclass

I'm trying to cast an Object into a class instance. The Object of the classes instance should of course inherit all the methods.

So here's my problem in sample code (2) because I can't exactly explain what I mean:

Class Fish {}
Class Dog {}

class Instances() {

    private Fish fish = new Fish();
    private Dog dog = new Dog();

    public Object getInstance(String className) {

        if( className.equals("fish") ) 

            return fish;

        else

            return dog;

    }

}

class test() {

    Instances in = new Instances();

    public static void main(String[] args) {

        // 1: works (transmits all the methods of fish)
        Fish fish = (Fish)in.getInstance("fish");

        // 2: doesn't work (fishObj only has access to the methods of an object and can't access the methods of Fish!)
        Object fishObj = null;
        fishObj = (Fish)in.getInstance("fish");

    }

}

Thank you in advance!

Best Solution

When you assign an object reference to a variable, any further operations you'll do with the reference variable are limited to the ones that are defined for its type.

So you can assign a Fish to an Object variable. But as long as you use the Object variable, you can only use methods that are defined in Object, such as toString(), hashCode() etc.

But you noted in your comments that you want to run a similar method in two classes. I assume that means your Dog and Fish classes have a method with similar names, parameters and return type, for example getLegCount() which would return 4 for Dog and 0 for Fish.

When this situation arises, you either have to declare both types as subclasses of another class, that has the required method:

public abstract class Animal {

    public abstract int getLegCount();

}

class Fish extends Animal {

    @Override
    public int getLegCount() {
        return 0;
    }
}

And then the return type from your getInstance() should be Animal, not Object. And you put the result in an Animal variable, and then you can use the getLegCount() method.

Another option is to define the required common methods as an interface. It works the same way, and is preferable if there are no implementation details in the expected Animal type, only method definitions:

public interface Animal {

    int getLegCount();

}

class Fish implements Animal {
    @Override
    public int getLegCount() {
        return 0;
    }
}

Again, you would declare your return type from getInstance as Animal and your variable as Animal rather than Object.