[英]Why do I get an error when I try to call a subclass method inside a baseclass method?
here is my code:这是我的代码:
public class Main {
public static void main(String args[]) {
A a = new A();
a.baseMethod();
}
}
class B{
public void baseMethod(){
System.out.println("B");
this.subMethod();
}
}
class A extends B{
public void subMethod(){
System.out.println("A");
}
}
/MyClass.java:14: error: cannot find symbol this.subMethod(); /MyClass.java:14: 错误:找不到符号 this.subMethod();
^ symbol: method subMethod() 1 error ^ 符号:方法 subMethod() 1 错误
I think that "this" refers to the object "a", if I put that in main it works, and class Main doesn't see class A as class B doesn't, so why can't I call the subclass method?我认为“this”指的是对象“a”,如果我把它放在 main 中它可以工作,并且类 Main 不会看到类 A,而类 B 不会,那么为什么我不能调用子类方法? Thank you very much非常感谢
Actually in this scenario, Super class (class A) can access the methods reside in base class (class B) but base class doesn't.实际上在这种情况下,超类(A 类)可以访问驻留在基类(B 类)中的方法,但基类不能。 If you want to access the base class (class B) methods by calling object of super class (class A), you can.如果你想通过调用超类(A类)的对象来访问基类(B类)的方法,你可以。 However, If you want to access super class (class A) methods by calling object of base class, you should have implemented the same method signature in super class.但是,如果要通过调用基类的对象来访问超类(A 类)方法,则应该在超类中实现相同的方法签名。 "this" keyword represents the same object reference where it is called (in your case class B object). “this”关键字表示调用它的相同对象引用(在您的情况下是 B 类对象)。
After having method (baseMethod) with same signature in both classes, you can test it by A a = new A();
在两个类中具有相同签名的方法(baseMethod)后,您可以通过A a = new A();
对其进行测试A a = new A();
and A b = new B();
和A b = new B();
. .
Keep coding :)继续编码:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.