简体   繁体   中英

Interface methods are not recognized when declaring parent class

it is quite hard for me to title this Thread. Feel free to fix this.

But here is my problem I have a abstract class and a parent that extends from the abstract class. I want one of the parents to have 2 more methods and call them in the Main Class. I thought about using an Interface to solve this but this does not work.

Here is the scenario:

My Abstract class

public abstract class AbstractClass {

    public abstract void method1();
}

My Interface for the parent class

public interface IInterface {
    void method2();
}

My Parent Class

public class ParentClass extends AbstractClass implements IInterface{

    @Override
    public void method1() {
        // TODO Auto-generated method stub
    }

    //This is the additional method i want to use
    public void method2() {
    
    }
}

My Main Class

public class MainClass {

static AbstractClass a;
static boolean condition = true;

public static void main(String[] args) {
    
        if(condition) {
            a = new ParentClass(); // This class should contain the additional method
        }
        else{
            a = new AnotherParentClass();
        }

        a.method2(); <- This does not work. There is only method1()
    }

}

How do i accomplish this kind of Structure? The Abstract class has only the basis of the parent class. But i also want to give a parent class extra abilities but want to work with the Abstract class in the main so i dont have to create multiple isntances of a class.

Any tips are appreciated

regards Nuri

a is statically typed AbstractClass and thus you see only its methods. The compiler cannot know that the runtime type has any other methods.

Suppose you declared another class ParentClass3 extends AbstractClass that did not implement IInterface ?

The only solution is to cast to IInterface at the point of reference. Then at runtime it will either invoke the method (if the object is the correct type) or throw ClassCastException .

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