Reputation: 7788
I have a rather basic question about interfaces, something I'm rather new too. I typically would instantiate my class with an overloaded constructor. I'm now trying to use interfaces and wondering how I would populate my constructor. Would I just use something like setSomeMethod(arguement1, arguement2) in my interface to populate my attributes?
I'd also like to note I'm using "Tapestry5" framework with service Injection. Example
public class Main {
@Inject
private Bicycle bicycle;
public Main() {
//Not sure how to pass constructor variables in
this.bicycle();
}
}
Interface
public interface bicycle {
public void someMethod(String arg1, String arg2);
}
Impl Class
public class MountainBike implements bicycle {
private String arg1;
private String arg2;
public MountainBike() {
//Assuming there is no way to overload this constructor
}
public void someMethod(String arg1, String2 arg2) {
this.arg1 = arg1;
this.arg2 = arg2;
}
}
Then how do you handle extended classes? I'm not sure how to populate the extended class constructor.
public class MountainBike extends BicycleParts implements bicycle {
private String arg1;
private String arg2;
public MountainBike() {
//Assuming there is no way to overload this constructor
//Not sure where to put super either, but clearly won't work here.
//super(arg1);
}
public void someMethod(String arg1, String2 arg2) {
this.arg1 = arg1;
this.arg2 = arg2;
//Assuming it doesn't work outside of a constructor, so shouldn't work
//here either.
//super(arg1);
}
}
public class BicycleParts {
private String arg1;
public void BicycleParts(String arg1) {
this.arg1 = arg1;
}
}
Thanks in advance.
Upvotes: 0
Views: 7535
Reputation: 159784
First off, your bicycle
method should be declared with a return type:
public void someMethod(String arg1, String arg2);
Interfaces define a contract for methods and not how objects are instantiated. They can also define static variables.
To use someMethod
in your MountainBike constructor, you could make the call in the constructor:
public MountainBike(String arg1, String arg2) {
someMethod(arg1, arg2);
}
Wrt, your question on extending the class, the super statement must appear as the very first statement in the constructor i.e.:
public class MegaMountainBike extends BicycleParts implements bicycle {
public MegaMountainBike() {
super("Comfy Saddle");
// do other stuff
}
Upvotes: 4
Reputation: 39451
You seem to be confused. Java the language defines constructors and methods. Constructors have special restrictions and cannot be put in an interface, and are implicitly called whenever you do a new
statement. Since constructors cannot be placed in interfaces, the common practice is to use factory methods instead.
Upvotes: 2