Good way to implement a child class - java

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();

Related

Java invoke child method from parent object

I've got next situation:
There is an abstract class
public abstract class SuperClass {
public abstract void getString();
public abstract void method2();
}
public class InheritClass1 extends SuperClass {
#Override
public void getString(){...};
#Override
public void method2(){...};
}
public class InheritClass2 extends SuperClass {
#Override
public void getString{...};
#Override
public void method2(){...};
public void customMethod(){...};
}
There is another class that has a method that accepts SuperClass object as an argument. Depending on what kind of String is returned from getString I perform different actions. My case is that I am trying to call a child method while the object is of parent class:
public class Processor {
public String method(SuperClass type) {
switch (type.getString()) {
case "1":
return "OK"
case "2":
return ((InheritClass2) type).customMethod()
}
}
I do understand that this is BAD DESIGN, could you please help me with finding the best solution for this problem. Maybe generics are suitable in this case somehow. Also the thing is that customMethod() should be a part of not all classes.
Since only some (sub)classes implements customMethod, I would suggest to create an interface that contains this method:
public interface CustomInterface {
public String customMethod();
}
Your SuperClass can then remain just as it is. Only the subclasses/child classes that have customMethod, would then extend your SuperClass as well as implement this CustomInterface. This way, the child classes that do not implement CustomMethod (does not have the method in their class, such as InheritClass1 in your example), also remain just as they are.
Only child classes that have CustomMethod, such as InheritClass2 would then need to change slightly by saying it implements this new interface:
public class InheritClass2 extends SuperClass implements CustomInteface {
// the rest stays the same
}
Then in the section where you want to do the casting, you rather do the following:
public class Processor {
public String method(SuperClass type) {
switch (type.getString()) {
case "1":
return "OK"
case "2":
String s = "";
if (type instance of CustomInterface) {
s = (CustomInterface type).customMethod();
}
return s;
}
}
}
Using the interface in this way will help that you can implement all child classes and not just one as implementing the CustomInterface, and thus, all child classes will work with using instanceof and casting to the interface to call customMethod() - you won't have to handle each child that needs this method separately.
NOTE: Your code is clearly simplified example, it is unclear if the getString() method is just returning an identifier of the child classes in order for you to know which ones you can cast and then call custom Method on... If this is the purpose of your switch and getString methods - to identify which types implement the customMethod() and to call that method, and for any child class that does not have that method to return just "OK" - then you could instead do the following:
public class SubClass1 extends SuperClass implements CustomInterface {
// other mehtods...
public String CustomMethod() { return "SomeString1"; }
}
public class SubClass2 extends SuperClass {
// other methods...
// this subclass does not have the CustomMethod()
}
public class SubClass3 extends SuperClass implements CustomInterface {
// other methods...
public String CustomMethod() { return "SomeString3"; }
}
Then your Processor could look like this:
public class Processor {
public String method(SuperClass type) {
return (type instanceof CustomInterface) ? ((CustomInterface) type).CustomMethod() : "OK";
}
public static void main(String[] args) {
Processor p = new Processor();
SuperClass obj1 = new SubClass1();
SuperClass obj2 = new SubClass2();
SuperClass obj3 = new SubClass3();
System.out.println(p.method(obj1)); // prints: "SomeString1"
System.out.println(p.method(obj2)); // prints: "OK"
System.out.println(p.method(obj3)); // prints: "SomeString3"
}
}
If you don't understand the ternary operator then you can read about it here That's the condition ? exprTrue : exprFalse syntax. It's a short if else statement basically.
You can create an interface, with default custom method implementation, like:
interface A {
default String customMethod() {
return "";
}
}
And abstract class will implement this interface:
public abstract class SupperClass implements A {
public abstract String getString();
public abstract void method2();
}
Bad design will cause you to get bad answers. If you don't want to cast your object to a child object. You could use reflection.
import java.lang.reflect.Method;
public class Processor {
public String method(SuperClass type) {
Method[] methods = type.getClass().getMethods();
for (Method m : methods) {
if (m.getName().equals("customMethod")) {
try {
return m.invoke(type);
} catch (Exception ex) {
// throw
}
}
}
return "OK";
}
}
Depending on your design you could apply:
if (type instanceof InheritClass2.class) return type.customMethod();
or
if (type.getClass() == InheritClass2.class) return type.customMethod();

Pass variable to one subclass

I'm a non-programmer with a very minimal coding exposure, but I'd like to modify an existing code base. I've greatly simplified the code I'm working with below. Please let me know if I can provide any further information or if this makes no sense at all! Vocab is hard. :)
In ClassA, I'm instantiating a subclass of ClassB. The change I'd like to make requires that a new variable, "myVar" (set in ClassA), is available to subclass ClassC but not subclass ClassD. What would be the most appropriate way to make that variable available to ClassC?
ClassA:
public class ClassA {
private String myVar = "hi";
private String myStuff = "bye";
private int myOption = 1;
private String getMyClass(String myStuff) throws Exception {
final MyClassChoice myClass = getMyClassChoice(myOption);
return myClass.getResponse(myStuff);
}
private MyClassChoice getMyClassChoice(myOption) {
switch(myOption) {
case 1:
return new ClassC();
case 2:
return new ClassD();
}
}
}
ClassB:
public class ClassB {
public abstract String getResponse(String myStuff) throws IOException;
}
ClassC:
public class ClassC extends ClassB {
// do stuff with myStuff
// do stuff with myVar
}
ClassD:
public class ClassD extends ClassB {
// do stuff with myStuff
}
You either pass it to the constructor when instantiating the object and save it in an instance variable,
public class ClassA {
// ...
private MyClassChoice getMyClassChoice(myOption) {
switch(myOption) {
case 1:
return new ClassC(myVar);
case 2:
return new ClassD();
}
}
}
public final class ClassC extends ClassB {
private String myVar;
// constructor:
public ClassC(String myVar) {
this.myVar = myVar;
}
// do stuff with myStuff
// do stuff with myVar
private void doStuff() {
System.out.println(myVar);
}
}
Or you pass it to the method when you use it,
public final class ClassA {
// ...
public void someMethodUsingClassCDoStuff() {
myClass.doStuff(myVar);
}
}
public final class ClassC extends ClassB {
// do stuff with myStuff
// do stuff with myVar
public void doStuff(String myVar) {
System.out.println(myVar);
}
}
First of all, make your variable myVar in calss A protected.
Put your class A,B,C in the same package.
Put your class D in a different package.

Abstract callback in reflection method of java

I have a class in jar of which I want to invoke a method. But that method has parameter of abstract class and that abstract class is inner method of class in jar. AbstractClassA is a HIDDEN class. Here is code:
public class A{
private invokeThisMethod(AbstractClassA object){
}
public abstract class AbstractClassA {
public void update(int remaining){}
}
}
public class myClass{
//using Reflection get object of class A
objectOfClassAusingReflection.inovke("invokeThisMethod", params)
}
Problem here is how do I create concrete implementation of AbstractClassA to pass in invoke method and get update method callbacks ?
Something like this should work:
AbstractClassA a = new AbstractClassA() {
public void update(int remaining) {... do something...}
};
objectOfClassAusingReflection.inovke("invokeThisMethod", a);
You cannot create an instance of abstract class or any interface at runtime.
Instead create an anonymous class for this.
public abstract class A {
public void fun(){....}
public abstract void absFun();
}
public class MyClass {
objectOfClassA = new A(){
public void absFun(){...}
}
}
Or you can first create implementation for that abstract classes for which you will have to create another class extending A
class AWrapper extends A {
public class ImplementationClassA extends AbstractClassA {
// override abstract functions...
}
}
Now you can use this Awrapper class
AWrapper wrapperObj = new AWrapper();
A obj = wrapperObj; // just to make it clear that A can hold wrapperObj as it is implementation of it.
A.AbstractClassA absObj = wrapperObj.new ImplementationClassA();
...
objectOfClassAusingReflection.inovke("invokeThisMethod", params)
Below code should work--
Here, i used anonymus classes for both outer and inner class and then with the help of getdeclatedMethod called your update method.
"TestAbs" is your jar class--
public abstract class TestAbs {
private void invokeThisMethod(AbstractClassA object) {
}
public abstract class AbstractClassA {
public void update(int remaining) {
}
}
}
Then calling your jar class from "TestAbs1" like below--
public class TestAbs1 {
public static void main(String[] args) {
TestAbs.AbstractClassA abs = new TestAbs() {
AbstractClassA a = new AbstractClassA() {
public void update(int remaining) {
System.out.println("Inside update method : " + remaining);
}
};
}.a;
try {
int i = 1;
Class<?> class1 = Class.forName("app.test.mytest.TestAbs$AbstractClassA"); -- (*Getting instance of inner class*)
System.out.println(class1.getDeclaredMethod("update", int.class));
class1.getDeclaredMethod("update", int.class).invoke(abs, i);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The output i got is --
public void app.test.mytest.TestAbs$AbstractClassA.update(int)
Inside update method : 1
Answer to your Comment:-
What I understood from your comment is that, you wanted to call method from abstractClass which is hidden in outerclass.
As per my understanding, there is one way like below--
public abstract class TestAbs {
private void invokeThisMethod(AbstractClassA object) {
}
private abstract class AbstractClassA { --- your hidden class
public void update(int remaining) {
}
}
public class ImplementedClass extends AbstractClassA{ -- use implemented class here
....
...
}
}
And after that, use your ImplementedClass the same way mentioned above.
You can find reference example for private inner class here from java docs.
Note: In your question context, since your inner class and outer class is in jar, so I think it is difficult for you add implementation class in your jar.
In case, you find any alternatives, please let all knows about this;
thanks.

Calling method from abstract class

I have the following abstract class
public abstract class ReturnAgentFromTab extends BasePage{
#Persist("session")
public abstract Agent getAgent();
public abstract void setAgent(Agent agent);
#InjectObject("spring:agentApplicationModeResolver")
public abstract AgentApplicationModeResolver getAgentApplicationModeResolver();
.... more #InjectObject()
public void nextPage(IRequestCycle cycle) {
setApplicationModeUsingAgentStatus(getAgent());
AgentSearchNavigationManager navManager = getAgentSearchNavigationManagerFactory().getAgentSearchNavigationManager();
FlowStage stage = getFlowStage();
if (stage == null) {
setApplicationModeUsingAgentStatus(getAgent());
stage = getUserDefaultFlowStageService().getDefaultFlowStage(UserHolder.getUser(), getVisitClass().getApplicationMode());
}
Class nextPageClass = navManager.getNextPage(getUserDefaultFlowStageService());
String nextPageQualifier = getUserDefaultFlowStageService().getPageQualifier(getAgent(), nextPageClass, getVisitClass().getApplicationMode());
IPage nextPage = getPageUtils().getPage(nextPageClass, nextPageQualifier);
if ((getFlowStage() instanceof PSDFlowStage)) {
nextPageQualifier = getFlowStage().getValue();
}
nextPage = getPageUtils().getPage(nextPageClass, nextPageQualifier);
if (navManager instanceof NameBasedAgentSearchNavigationManager && nextPageClass != SignOffStatusPage.class) {
NameBasedAgentSearchNavigationManager nameBasedNavManager = (NameBasedAgentSearchNavigationManager) navManager;
String nextPageName = nameBasedNavManager.getNextPageName(stage);
if (!nextPageName.equals(nextPageClass.getSimpleName())) {
nextPage = getPageUtils().getPage(nextPageName, nextPageQualifier);
}
}
if (isNextPageActivateAgentGeneral(nextPage)) {
initialisePageLink(nextPageClass, nextPage);
}
((WuamsBasePage) nextPage).init(getAgent().getAgentId());
getPageUtils().navigateTo(nextPage);
}
private void setApplicationModeUsingAgentStatus(Agent agent) {
getVisitClass().setApplicationMode(getHomeLinksFactory().getRegionHomeLinksService().getApplicationMode(agent));
}
private boolean isNextPageActivateAgentGeneral(IPage nextPage) {
return nextPage instanceof ActiveAgentGeneralPage;
}
private void initialisePageLink(Class nextPageClass, IPage nextPage) {
if (getVisitClass().getPageLink() == null) {
getVisitClass().setPageLink(PageLinkUtil.getPageLinkMessageKeyFromPageClass(nextPageClass,
getUserDefaultFlowStageService().getDefaultFlowStage(UserHolder.getUser(), getVisitClass().getApplicationMode()).getValue()));
}
}
}
What I want to do is call my nextPage(cycle) from another class that is abstract and extends ReturnAgentFromTab, but when I try
public abstract class DoSomethingWithAgent extends ReturnAgentFromTab {
#Persist("session")
public abstract ReturnAgentFromTab getReturnAgentFromTab();
public abstract void setReturnAgentFromTab(ReturnAgentFromTab returnAgentFromTab);
....
getReturnAgentFromTab().nextPage(cycle);
I get a null pointer exception, I know this is because I am not actually setting ReturnAgentFromTab anywhere but I do not understand how to set it using abstract classes. Can anybody help?
If ye need more code just ask
The point of abstract classes is to simply not implement certain things, such as providing certain objects. The method getReturnAgentFromTab() is a perfect example: the class itself does not care where that object comes from because that is the sole responsibility of the subclass. So extend that class, write that method, and all of a sudden the base class does its thing.
well, you cant intialize abstract class, the only way is to make some other concrete class extend your abstract class, and call the non abstract method with the concrate classes instance.
abstarct class ABS1 {
//abstract methods
//concreate method
public void concMethod() {
}
}
public class ABS1Impl extends ABS1 {
//implement all the abstract methods
}
public abstract class ABS2 {
ABS1 abs = new ABSImpl();
abs.concMethod //
}

Super class which uses the values from children

I wanted to implement a method in a abstract class that is called by the inherited classes and uses their values.
For instance:
abstract class MyClass{
String value = "myClass";
void foo(){System.out.println(this.value);}
}
public class childClass{
String value="childClass";
void foo(){super.foo();}
}
public static void main(String[] args){
new childClass.foo();
}
This will output "myClass" but what I really want is to output "childClass". This is so I can implement a "general" method in a class that when extended by other classes it will use the values from those classes.
I could pass the values as function arguments but I wanted to know if it would be possible to implement the "architecture" I've described.
A super method called by the inherited class which uses the values from the caller not itself, this without passing the values by arguments.
You could do something like this:
abstract class MyClass {
protected String myValue() {
return "MyClass";
}
final void foo() {
System.out.println(myValue());
}
}
public class ChildClass extends MyClass {
#Override
protected String myValue() {
return "ChildClass";
}
}
and so on
This is a place where composition is better than inheritance
public class Doer{
private Doee doee;
public Doer(Doee doee){
this.doee = doee;
}
public void foo(){
System.out.println(doee.value);
}
}
public abstract class Doee{
public String value="myClass"
}
public ChildDoee extends Doee{
public String= "childClass"
}
...
//Excerpt from factory
new Doer(new ChildDoee);
I believe you are asking whether this is possible:
public class MyClass {
void foo() {
if (this instanceof childClass) // do stuff for childClass
else if (this intanceof anotherChildClass) // do stuff for that one
}
}
So the answer is "yes, it's doable", but very much advised against as it a) tries to reimplement polymorphism instead of using it and b) violates the separation between abstract and concrete classes.
You simply want value in MyClass to be different for an instance of childClass.
To do this, change the value in the childClass constructor:
public class childClass {
public childClass() {
value = "childClass";
}
}
Edited:
If you can't override/replace the constructor(s), add an instance block (which gets executed after the constructor, even an undeclared "default" constructor):
public class childClass {
{
value = "childClass";
}
}

Categories