Madalina Gheboianu Madalina Gheboianu - 4 months ago 9
Java Question

Error in java at adding methods

I read that you can add extra methods for an object, or override the abstract methods in this way, yet I have an error. Can you tell me if this is even possible or what I have done wrong?

public abstract class Pesti {
public abstract void ud();
}

public class EX2 {
public static void main(String[] args) {
Pesti p = new Pesti() {
public void ud() {
System.out.println("Pestele este ud!");
}

public void inn() {
System.out.println("Innoata!");
}
};
p.ud();
p.inn();
}
}


It tells me that it cannot find method
inn
.

Answer

What you are doing is creating an anonymous sub-class of your Pesti. However, since your p variable is of type Pesti, you can only call methods declared in the Pesti class (or any of its super-classes). Therefore you can call ud(), but not inn().

If you could cast p to the type of the sub-class, you could have called inn(), but since this is an anonymous sub-class instance, you can't cast to that type.

You could declare inn() as an abstract (or concrete) method in Pesti. Then your code would pass compilation, and the implementation of this method in the anonymous sub-class instance will be executed.

public abstract class Pesti {
    public abstract void ud();
    public abstract void inn();
}