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
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");
}
}
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With