Search code examples
javainterfacesubclassinterface-implementation

Convert object to interface and back in java


I have an interface A that has a method:

public interface A { public double doSth(); }

and a B class that implements A and has some other method:

    class B implements A {
        private String name;

        @Override
        public double doSth();//returns the lenght of the name

        public void getName(){}
}

In the main class, I have an array list of A-type objects and a method that looks for an object from an array list that has the greatest value of doSth() and returns a reference to this object.

public class Main {

    public static void main(String[] args) {
         ArrayList<A> array = new ArrayList<>();

}

public static A a(ArrayList<A> array){
 A aObject = null;
    double temp = 0;
    for (A bObject: array){
        if(bObject.doSth()>temp){
            temp = aObject.doSth();
            aObject = bObject;
        }
    }
    return aObject;

}

What I need to do is to use this method in main and then print the name of the object that was returned as an A-type object by a method. Is it possible to do this? Is there any possibility to convert the A object back to B class?


Solution

  • Yes. Using instanceof you can test what type of class implemented your interface then you cast it to that class.

    For example:

    List<A> myList = getMyList();
    
    A foo= a(myList);
    
    if (foo instanceof B) {
      B bar = (B)foo;
      System.out.println(bar.getName());
    }