Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Abstract Class -- cannot find symbol - method ERROR

I am a newbie to Java programming and need some help. I have an abstract class with one non-abstract method and one abstract method. From the abstract class (class A) I am calling a method of a subclass (class B) by using "this.getSize();" (I understand "this" to mean the object type that is invoking the method. So in this case -B) but I am getting an error saying this when trying to compile class A:

" Cannot find symbol - method getSize() "

I am thinking maybe this is due to the fact that I am calling this from an abstract method but I am not sure. Please help.. Thanks.

Here is my CODE:

abstract class A{

    public int size()
    {
        return this.getSize();
    }

    //abstract method
    abstract void grow(int f);
}


class B extends A{
    private int size = 1; //default set of size

    public int getSize(){ return size; }

    public void grow(int factor)
    {
        size = size * factor;
    }
}
like image 945
user1899872 Avatar asked Jun 30 '26 04:06

user1899872


2 Answers

The super class cannot reference methods from the implementing class. You need to declare getSize as an abstract method.

A.class

abstract class A {

    public int size() {
        return this.getSize();
    }

    abstract public int getSize();

    // abstract method
    abstract void grow(int f);

}

B.class

class B extends A {
    private int size = 1; // default set of size

    public int getSize() {
        return size;
    }

    public void grow(int factor) {
        size = size * factor;
    }

    public static void main(String[] args) {
        B b = new B();
        System.out.println(b.getSize()); //Prints 1
    }
}
like image 65
Kevin Bowersox Avatar answered Jul 01 '26 17:07

Kevin Bowersox


You didn't declare any getSize() method in A. I think you mean to declare it abstract in A.

public abstract int getSize();

Then you could call the method.

like image 35
rgettman Avatar answered Jul 01 '26 17:07

rgettman