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;
}
}
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
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With