Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Compiler error even after downcasting

    An example from the SCJP(OCP) book:

    Java Code:
    class Animal {
    	void makeNoise() {System.out.println("generic noise"); }
    }
    class Dog extends Animal {
    	void makeNoise() {System.out.println("bark"); }
    	void playDead() { System.out.println("roll over"); }
    }
    class CastTest2 {
    	public static void main(String [] args) {
    		Animal [] a = {new Animal(), new Dog(), new Animal() };
    		for(Animal animal : a) {
    			animal.makeNoise();
    			if(animal instanceof Dog) {
    				Dog d = (Dog) animal;  
    				animal.playDead();       // try to do a Dog behavior ?
    			} }
    	} }
    The book states that the above code will compile if there is a downcast in the line 14 . But there is a compiler error saying playDead method is not defined for type animal even after downcasting. Someone pls help.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: Compiler error even after downcasting

    Java Code:
    Dog d = (Dog) animal;  
    animal.playDead();       // try to do a Dog behavior ?
    Are you sure the book is using the "animal" reference to call the playDead() method?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    Join Date
    Aug 2013
    Posts
    55
    Rep Power
    0

    Default Re: Compiler error even after downcasting

    My mistake. It uses dog reference.

Similar Threads

  1. DownCasting
    By yanivdan98 in forum New To Java
    Replies: 2
    Last Post: 02-25-2013, 10:07 AM
  2. Compiler error
    By Nikpatel in forum NetBeans
    Replies: 2
    Last Post: 04-26-2012, 10:39 AM
  3. Compiler Error, Please any help?
    By Liberate in forum New To Java
    Replies: 4
    Last Post: 02-04-2012, 08:19 PM
  4. downcasting in java
    By guest_user in forum New To Java
    Replies: 8
    Last Post: 05-23-2011, 03:08 PM
  5. Replies: 3
    Last Post: 01-23-2009, 09:53 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •