简体   繁体   中英

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();
^ symbol: method subMethod() 1 error

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? 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. If you want to access the base class (class B) methods by calling object of super class (class A), you can. 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. "this" keyword represents the same object reference where it is called (in your case class B object).

After having method (baseMethod) with same signature in both classes, you can test it by A a = new A(); and A b = new B(); .

Keep coding :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM