Search code examples
javaoopinheritancemethodsabstract-class

Method not found in derived class inherited from abstract class


abstract class superclass {
  public abstract void method();
}
class subclass extends superclass {
  public void method() {
    //do something
  }
  public void newMethod() {
    //do something
  }
}
public class mainclass {
  public static void main(String[]args) {
    superclass abc = new subclass();
    abc.method();
    abc.newMethod(); //cannot find symbol error
  }
}

In the above example, can new methods be not written in the derived class of an abstract class? If I do that, it raises an error.


Solution

  • When extending a Superclass you can in fact add more methods. Hoevery in this case you assign your new subclass() to a variable of the type superclass which means that you will only have access to the methods wich are a part of that type. In this case that's only method(). If you want to use both methods you should write instead:

    subclass abc = new subclass();
    

    or cast it on demand:

    ((subclass) abc).newMethod();