A language without downcasting

Programming, for all ages and all languages.
seuti
Member
Member
Posts: 74
Joined: Tue Aug 19, 2014 1:20 pm

Re: A language without downcasting

Post 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.
Post Reply