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:
我是Java编程的新手,需要一些帮助。我有一个抽象类,一个非抽象方法和一个抽象方法。从抽象类(类A)我通过使用“this.getSize();”调用子类(类B)的方法(我理解“this”是指调用该方法的对象类型。所以在这种情况下-B)但是在尝试编译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 个解决方案
#1
4
The super class cannot reference methods from the implementing class. You need to declare getSize
as an abstract method.
超类不能引用实现类中的方法。您需要将getSize声明为抽象方法。
A.class
一类
abstract class A {
public int size() {
return this.getSize();
}
abstract public int getSize();
// abstract method
abstract void grow(int f);
}
B.class
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
}
}
#2
1
You didn't declare any getSize()
method in A
. I think you mean to declare it abstract
in A
.
你没有在A中声明任何getSize()方法。我认为你的意思是在A中声明它是抽象的。
public abstract int getSize();
Then you could call the method.
然后你可以调用该方法。
#1
4
The super class cannot reference methods from the implementing class. You need to declare getSize
as an abstract method.
超类不能引用实现类中的方法。您需要将getSize声明为抽象方法。
A.class
一类
abstract class A {
public int size() {
return this.getSize();
}
abstract public int getSize();
// abstract method
abstract void grow(int f);
}
B.class
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
}
}
#2
1
You didn't declare any getSize()
method in A
. I think you mean to declare it abstract
in A
.
你没有在A中声明任何getSize()方法。我认为你的意思是在A中声明它是抽象的。
public abstract int getSize();
Then you could call the method.
然后你可以调用该方法。