简体   繁体   中英

Force Java upper cast class

It is possible to force an upper cast type in java? See the example.

public class Animal{}

public class Dog extends Animal{}

Dog dog = new Dog();  
Animal test = dog;

What I have: (test instanceof Dog) and (test instanceof Animal) return true.
What I want: (test instanceof Dog) == false and (test instanceof Animal) == true

Or the only way is creating a constructor for animal passing a dog? I was trying to avoid to create a constructor because I had a complex object, with a lot of getters/setters.

Thanks.

I don't know why you would care if an object is an Animal but not a Dog , after all, a Dog is an Animal . Anything that can apply to a Dog should be applicable to an Animal , else there is a design issue.

But if you must determine that, then call getClass() (defined by Object ) to get the Class object, then compare it with Animal.class .

if (Animal.class == test.getClass())
if (test.getClass() == Animal.class) {...

When you "extends", you are saying Dog is an Animal. I see the behavior is correct as you coded.

If you had-

class Animal {}
class Human {}

class Cat extends Animal{}
class Child extends Human {}

Cat is an Animal.

Child is A Human.

Cat is NOT a Human.

Child is NOT an Animal.

Test is an instance of Dog, and test is an instance of animal.

This isn't a problem, its one of the funadmentals of OO programming. Polymorphism.

Whatever reason you have for ensuring the type is exactly of Type animal is likely due to poor design.

There is no way of changing what type the instance is. you can use and instance of as if its an instance of animal.

Also a lot of setters and getters shouldn't be too much of a problem and it shouldn't have to require an input of Dog. Just have a constructor that copies all the fields in Animal directly (you can access fields directly with other objects of the same class) and it would be able to accept dog as an argument.

public class Animal{
    private int[] data;
    public Animal(Animal a){
        data=a.data;
        ...
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM