+ 1
I am trying to cast but I can't find what is wrong, can you please help me
class Animal{ protected void makeSound(){ System.out.println("miou"); }; } class Cat extends Animal{ protected void makeSound(); } class Test{ public static void main(String[] args){ Animal a = new Animal(); ((Cat)a).makeSound(); } }
5 Respuestas
+ 2
class Animal{
protected void makeSound(){
System.out.println("miou");
};
}
class Cat extends Animal{
@Override
protected void makeSound(){
}
}
class Test{
public static void main(String[] args){
Animal a = new Animal();
a.makeSound();
}
}
+ 1
class Animal{
protected void makeSound(){
System.out.println("miou");
};
}
class Cat extends Animal{
@Override
protected void makeSound(){
System.out.println("Cat");
}
}
class Test{
public static void main(String[] args){
Animal a = new Animal();
try{
((Cat)a).makeSound();
}catch(ClassCastException ex){
System.out.println("An error has occurred");
}
/**
if you try to attribute an object of class Animal to an object of class Cat, and they are incompatible, you get a class exception.
Better not to do so.
**/
//A working variant that calls the makeSound Cat method
Cat c = new Cat();
c.makeSound();
}
}
0
@Aidos Zhakupov it doesn't cast Animal instance to it's subclass
0
misic
0
Any want to offer assistance in java one on one ?