Java多态报错:cannot find symbol,子类方法调用问题咨询
fetch() on Your Animal Reference? Hey there! I totally get why this is confusing—you can see the object is actually a Dog at runtime, but the compiler won’t let you call its unique method. Let’s unpack this step by step.
The Root of the Error: Compile-Time vs. Runtime Type
In Java, every reference variable has two key types:
- Compile-time type: This is the type you declare the variable to be (
Animalin your code:Animal doggie = new Dog();). The compiler only checks for methods that exist in this declared type. SinceAnimaldoesn’t have afetch()method, it throws that "cannot find symbol" error. - Runtime type: This is the actual type of the object the reference points to (
Doghere). That’s whydoggie.getClass().getName()outputsdog—it’s showing you the real object type when the code runs. But the compiler doesn’t care about this during compilation; it only enforces the contract of the declared parent class.
How to Fix It
You have two straightforward ways to call fetch() here:
1. Downcast the Reference
You can explicitly convert the Animal reference to a Dog type (this is called downcasting). Wrap the variable in parentheses with the target type to access the subclass method:
public class tester { public static void main(String args[]){ Animal doggie = new Dog(); // Downcast to Dog to access fetch() ((Dog) doggie).fetch(); doggie.eat(); doggie.roam(); } }
To avoid a ClassCastException (if the reference ever points to a non-Dog Animal subclass later), add a safety check first:
if (doggie instanceof Dog) { ((Dog) doggie).fetch(); }
2. Add the Method to the Parent Class (If It Makes Sense)
If fetch() is a behavior that fits most (or all) Animal subclasses, you can define it in the Animal class—either as an abstract method (turning Animal into an abstract class) or with a default empty implementation:
// Modified abstract Animal class public abstract class Animal { String family; String name; public void eat() { System.out.println("Ghap Ghap"); } public void roam() { System.out.println("paw paw"); } // Abstract method—subclasses must implement it public abstract void fetch(); }
Your Dog class would keep its fetch() implementation, and you could call doggie.fetch() directly without casting. This only makes sense if fetch is a universal Animal behavior though—if only Dogs do it, stick with downcasting.
Quick Style Tip
A small note: Java convention says class names should start with a capital letter. So animal → Animal, dog → Dog, tester → Tester. It’s not causing your error, but it’ll make your code easier to read for other Java devs!
内容的提问来源于stack exchange,提问作者Mrak Vladar

