+ 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(); } }

26th Mar 2018, 8:47 AM
Delcio Claudio Tchinanamata
Delcio Claudio Tchinanamata - avatar
5 Answers
+ 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(); } }
26th Mar 2018, 8:54 AM
Aidos Zhakupov
Aidos Zhakupov - avatar
+ 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(); } }
26th Mar 2018, 11:30 AM
Aidos Zhakupov
Aidos Zhakupov - avatar
0
@Aidos Zhakupov it doesn't cast Animal instance to it's subclass
26th Mar 2018, 10:41 AM
Delcio Claudio Tchinanamata
Delcio Claudio Tchinanamata - avatar
0
misic
26th Mar 2018, 5:56 PM
pierre wendel
0
Any want to offer assistance in java one on one ?
1st Apr 2018, 8:18 AM
Onesha Sappleton
Onesha Sappleton - avatar