Why are parentheses used around a class name in Java?

I came across some kind of code and can't figure out a certain aspect of this, although I did a great search!

My question is: why are classes sometimes declared in parentheses, for example, in the following code?

public class Animal {

    public static void hide() {
        System.out.println("The hide method in Animal.");
    }

    public void override() {
        System.out.println("The override method in Animal.");
    }
}

public class Cat extends Animal {

    public static void hide() {
        System.out.println("The hide method in Cat.");
    }

    public void override() {
        System.out.println("The override method in Cat.");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = (Animal)myCat;
        myAnimal.hide();
        myAnimal.override();
    }
}

where the focus is on this line of code, in particular:

            Animal myAnimal = (Animal)myCat;

I believe this is due to the fact that one class extends another, but I'm not sure what the class defined in parentheses means.

Any help on this is appreciated. Thank you in advance.

+5
source share
4 answers

What you see is a roll to tell the compiler that he can assign Cat to the animal.

, , , , , , (, float). , Cat Animal; Cats , , , Cat .

+8

- myCat, Cat, Animal.

, Animal.

Java.


@Sebastian Koppehel , - myAnimal variable ( Animal) , Animal.

+7

, , , , , , . Java . , .

+1

You explicitly guarantee the compiler / runtime that the type of the cat link you are passing is the type of Animal. In java it is called casting .

At run time, if this contract is not executed (this means that there is no relationship between the cat and animal), you will receive ClassCastException.

0
source

All Articles