3

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;
    }
}

2 Answers 2

4

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.