So I have about 10-15 classes (this could grow to a much larger number in time) and they all have fairly similar variables within them:
temp
conditions
humidity
load
..And stuff like that. I'm looking to implement a parent class (abstract) to better manage this since they are all runnable.
There's a part where I call a constructor for each of them and it's... just bad.
public ThreadHandler(NH.NHandler NSH, int threadNum){
this.threadNum=threadNum;
this.NSH = NSH;
}
public ThreadHandler(OPA.OpaHandler SgeSH, int threadNum){
this.threadNum=threadNum;
this.OpaSH = OpaSH;
}
public ThreadHandler(SGE.SgeHandler SgeSH, int threadNum){
this.threadNum=threadNum;
this.SgeSH = SgeSH;
}
..... and on for 15
How would I implement a parent class to simply do
public ThreadHandler(objectType name, int threadNum){
//Do stuff
}
Thanks for any help.
You need to create an interface, say, IHandler with common methods and all handlers should implement this interface
public interface IHandler {
.... declare public methods
}
public NHandler implements IHandler {
.... implement all the methods declared in IHandler..
}
Now you can just have the following in ThreadHandler
public ThreadHandler(IHandler handler, int threadNum){ .... call the methods }
I have another example using abstract class
and extends
that to ChildClass
. I hope will help your problem.
ParentHandler.java
public abstract ParentHandler<T> {
public T obj;
public int threadNum;
// Declare the common variable here...
public ParentHandler(T obj, int threadNum) {
this.threadNum = threadNum;
this.obj = obj;
}
}
ChildHandler.java
public class ChildHandler extends ParentHandler<NH.NHandler> {
public ChildHandler(NH.NHandler nsh, int threadNum) {
super(nsh, threadNum);
}
}
Implement an interface, every "child" class will implement it, then you can declare an object of the interface type and create a method that returns the especific class based on something, like this.
public Interface ITest
{
string temp;
void Test(string param1, string param2);
}
public Class Class1 : ITest
{
void Test(string param1, string param2)
{
// DO STUFF
}
}
public Class Class2 : ITest
{
void Test(string param1, string param2)
{
// DO STUFF
}
}
And then:
public ITest GetClass(string type)
{
switch (type)
{
case "class1":
return new Class1();
case "class2":
return new Class2();
}
}
And you call it like
ITest obj = GetClass("class1");
obj.Test();
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.