Sean Cantwell
Sean Cantwell

Reputation: 31

Cannot find symbol: barkOnce() of location: variable d of type Object

class Main {
    public static void main(String[] args) {
       Object d = new Dog();
       d.barkOnce();
    }
}

class Dog
{
    private String voice;

    public void barkOnce()
    {
        System.out.println(voice);
    }
 }

When ever I run the program, I get an error in my output:

exit status 1 Main.java:4: error: cannot find symbol d.barkOnce(); ^ symbol: method barkOnce() location: variable d of type Object

After analyzing the error, I was clueless as to why the method couldn't be found. Can someone possibly explain what I might be missing here?

Upvotes: 0

Views: 1597

Answers (2)

kailoon
kailoon

Reputation: 2069

This is because you declared the variable "d" as type Object. Object does not have a barkOnce() method. You can cast it to Dog:

((Dog) d).barkOnce();

or declare it a Dog to begin with:

Dog d = new Dog();

Upvotes: 0

nbering
nbering

Reputation: 2800

Method barkOnce() is not part of the type Object. You should be able to compile with:

Dog d = new Dog()

When you cast to a base like Object, the compiler blocks you from using anything on the more specific type, unless you typecast back.

Upvotes: 1

Related Questions