How to resolve "main.java:7: error: cannot find symbol" error in Java?

Viewed 272

main.java file

package animal;
    class Main {    
        public static void main(String[] args) {
            System.out.println("Hello World!");
    
            animal dog = new animal();
            dog.bark();
        }
    
    }

animal.java file

public class animal {
    void bark() {
        System.out.println("Woof-Woof");
    }
}

The error I am getting.

enter image description here

Can someone please help, I am new to java?

2 Answers

Try remove package animal; from your Main.java file

So change your code from this:

package animal;   
    class Main {    
        public static void main(String[] args) {
            System.out.println("Hello World!");
    
            animal dog = new animal();
            dog.bark();
        }
    
    }

TO become like that:

class Main {    
        public static void main(String[] args) {
            System.out.println("Hello World!");
    
            animal dog = new animal();
            dog.bark();
        }
    
    }

Delete package because your animal file is not a package but just a class

class Main {    
    public static void main(String[] args) {
        System.out.println("Hello World!");

        animal dog = new animal();
        dog.bark();
    }

}

This link can help you to understand Java referencing a class in the same directory

But if want still using package, you can do like this:

//save by A.java  
package pack;  
public class A {  
    public void msg() {
        System.out.println("Hello");
    }  
}  

//save by B.java  
package mypack;  
class B {  
    public static void main(String args[]) {  
        pack.A obj = new pack.A();  //using fully qualified name  
        obj.msg();  
    }  
}

src: https://www.studytonight.com/java/package-in-java.php#:~:text=To%20import%20java%20package%20into,by%20directly%20using%20its%20name.

Related