Java can't find symbol from .class in the same

2019-08-01 06:21发布

问题:

I have two files: MyStringLog.java (which extends ArrayStringLog) and TestDriver.java in the same directory. Why doesn't TestDriver.java recognize the MyStringLog constructor from the MyStringLog class? In TestDriver.java I declare:

MyStringLog animals = new MyStringLog("animals");

This is supposed to construct a new MyStringLog object named animals, but I get 2 errors when I compile, both, that MyStringLog symbol is not found.

  • ArrayStringLog.java: http://pastebin.com/Z624DRcm
  • MyStringLog.java:http://pastebin.com/zaH2S3yg
  • TestDriver.java:

    public class TestDriver {
        public static void main(String[] args) {
            MyStringLog animals = new MyStringLog("animals");
            animals.insert("dog");
        }
    }
    

回答1:

I got this to roughly work. To do so...

for the file ArrayStringLog.java, I removed the implements StringLogInterface because I simply don't have access to that interface. After doing so, I removed the package ch02.stringLogs;. When I compiled this file with the package... still there, I recieved the error: Exception in thread "main" java.lang.NoClassDefFoundError: ArrayStringLog (wrong name: ch02/stringLogs/ArrayStringLog)

Then in MyStringLog.java, I removed the import ch02.stringLogs.*;. I then saved and compiled the code, and ran the TestDriver, to which I received no compilation errors.

This leads me to believe that your error stems from the package statement in ArrayStringLog.java.


To finally get a compilation, I put all four files (ArrayStringLog, MyStringLog, StringLogInterface, TestDriver) into the same directory, removed any package... statements, added back implements StringLogInterface to ArrayStringLog.java, compiled each one, and then ran TestDriver with an added toString method from which the output was:

Log: animals

1. dog
2. cat

Here was the test driver:

public class TestDriver {
    public static void main(String[] args) {
        MyStringLog animals = new MyStringLog("animals");
        animals.insert("dog");
        animals.insert("cat");

        System.out.println(animals.toString());
    }
}

To make clear, ArrayStringLog begins with:

public class ArrayStringLog implements StringLogInterface


回答2:

try adding import MyStringLog; to your file.

Also are you using packages? In which case it should be import <package_name>.MyStringLog;