简体   繁体   English

当我尝试在基类方法中调用子类方法时,为什么会出现错误?

[英]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.

相关问题 为什么基类调用子类的方法? - Why baseclass calls method of subclass? 为什么在使用超类引用调用子类方法时出现编译时错误? - Why do I get a compile-time error when calling a subclass method using superclass reference? 在引用其超类时如何调用子类的方法? - How do i call a method of a subclass when referencing its superclass? 调用start方法时为什么会出现编译错误? - Why do I get a compile error when calling start method? 当定义为BaseClass时,在ExtendedClass对象上调用BaseClass方法 - Call BaseClass method on ExtendedClass object when defined as BaseClass 当我尝试在主方法之外调用方法时发生NullPointerException - NullPointerException when I try to call a method outside my main method 为什么我不能从超类对象调用子类方法 - why can't i call a subclass method from a superclass object 当我尝试在没有主要方法的情况下在 class A 中调用 class B 的方法时出现错误 - Error appears when i try to call a method of class B in class A without main method 子类和方法-如何从子类调用方法? - subclass and method-How can i call a method from a subclass? 为什么从jsp页面而不是从main方法运行方法时出现错误? - Why do I get an error when running a method from a jsp page, but not from a main method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM