kamil kamil - 5 months ago 20
Java Question

methods after extending abstract class

I don't know exacly how to describe my problem so I'll make an example:

public abstract class A {

public abstract void methodToOverride();
public void methodNotToOverride() { }

}

public class B extends A {

@Override
public void methodToOverride() { }
public void someOtherMethodNotFromClassA() { }

}


now I need to do such thing in my code:

A object = new B();
object.someOtherMethodNotFromClassA();


but I get "Cannot resolve method error". Defining such method in the abstract class is not an option. Any clue?

Answer

This is not possible. While the object is of type B, the reference is of type A. Therefore, you are only able to access methods visible to class A.

If you change this:

A a = new B();

to this:

B a = new B();

you would be able to access someOtherMethodNotFromClassA. Another option would be to cast a to type B:

A a = new B();
((B)a).someOtherMethodNotFromClassA();
Comments