Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Given Interface with methods - how are parameters passed?

I tried to keep the code as generic as possible, this only represents the basic setup. I am a Java beginner trying to understand Interfaces, Classes and Methods. I did change the Interface name and Class names to make referencing them easier. I am fully aware that this code as it is won't compile. I am trying to understand the concept.

Given is an Interface, with an existing InterfaceClass and another class using the interface.

Interface:

public interface IInterface extends Comparable<IInterface>{    
    String getContent() throws DumbException;
}

Class:

public class InterfaceClass implements IInterface{
    public String getContent() throws DumbException {
        // here I would need a parameter (filepath) to get a file 
        // and read its content and return the content as string
        // however the interface doesn't provide a parameter for this
        // method. So how is this done?
    }
}

The class using the method:

public class Frame extends AbstractFrame {
    public void setDetails(IInterface details) {
        // This is the call I don't understand...
        details.getContent();     
    }
}

The part I don't understand is: How does the details object give any parameter to getContent()? I mean I don't even see this object being defined other than IInterface details

like image 946
CMA Avatar asked Mar 01 '26 15:03

CMA


1 Answers

Solution 1

You can redefine IInterface to

public interface IInterface extends Comparable<IInterface>{    
    String getContent(String filepath) throws DumbException;
}

public class InterfaceClass implements IInterface{
    public String getContent(String filepath) throws DumbException {
        // use filepath to get the file's content
    }
}

Usage is

public class Frame extends AbstractFrame {
    public void setDetails(IInterface details) {
        details.getContent("/path/to/some/folder");     
    }
}

Solution 2

You can't change IInterface but you add a constructor to InterfaceClass

public class InterfaceClass implements IInterface{
    private String filepath;

    public InterfaceClass(String filepath) {
        this.filepath = filepath;
    }

    public String getContent() throws DumbException {
        // use filepath to get the file's content
    }
}

Usage is

new Frame().setDetails(new InterfaceClass("path/to/some/folder"));
like image 178
Spotted Avatar answered Mar 03 '26 04:03

Spotted



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!