Page 2 of 2

Re: A language without downcasting

Posted: Fri Feb 13, 2015 3:11 am
by seuti
In Java we can use instanceof

Code: Select all

public abstract class Animal {
    public void eat() {
        System.out.println("nom nom nom");
    }
}

public class Cat extends Animal {
    public void meow() {
        System.out.println("meow!")
    }
}

public class Dog extends Animal {
    public void bark() {
        System.out.println("woof!");
    }
}

public class DowncastingTest {
    public static void main(String[] args) {
        // Animal someAnimal = new Cat();
        Animal someAnimal = new Dog();

        if(animal instanceof Dog)
            ((Dog) someAnimal).bark();

        if(animal instanceof Cat)
            ((Cat) someAnimal).meow();
    }
}
I think in C# the keyword is typeof.