Pass variable to one subclass - java

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.

Related

How to inherit the base class implementation of Parent class in my Child class?

Base class:
public class BaseClass
{
public void beforeClass
{
TestDataLoader loader = new TestDataLoader(); //some implementation here
readData = loader.fetchdata(...);
}
}
Class-1:
public class ClassA extends BaseClass
{
String a;
public void method1()
{
..
..
}
}
Class-2:
public class ClassB extends classA
{
String a1;
public void methodB(ClassA classA1)
{
if(classA1 == null)
{
//do nothing
}
classA1.method1();
}
}
The problem i see here is that i am not able use testDataLoader (for which the implementation is in BaseClass) of ClassA in my ClassB. I am able to access method1 of ClassA in my ClassB but i am not able to use the testDataLoader of ClassA in ClassB
Note: i cannot pass arguments to method1 of ClassA as it won't support arguments to be passed to it.
Could someone help me on this?

is it possible to declare a Java Class variable using getClass()?

All of the relevant classes in my application instantiate a version of the class Logger as logger = new Logger(). Any class can invoke it's instance of logger.setText(String text).
The writeText(Object parameter) method in ClassA is built to get the previously set string from each class instance of logger by invoking it's instance of logger.getText().
Currently I've placed a conditional inside wrtieText for each of the classes. This works, but can become an issue if I end up adding more classes. I want a catch-all writeText method to accommodate for any new classes that may be added.
The following is the currently working model. Beneath this, I have included the alternate version of ClassA, which attempts to do what I'm describing by using the getClass() method.
ClassA.java
public class ClassA {
public static void main(String[] args) {
ClassA classA = new ClassA();
classA.execute();
}
public void execute() {
ClassB doSomething = new ClassB();
writeText(doSomething);
ClassC doSomethingElse = new ClassC();
writeText(doSomethingElse);
}
public void writeText(Object parameter) {
if(parameter instanceof ClassB) {
ClassB x = (ClassB) parameter;
System.out.println(x.logger.getText() + "\n\n");
}
if(parameter instanceof ClassC) {
ClassC x = (ClassC) parameter;
System.out.println(x.logger.getText() + "\n\n");
}
if(parameter instanceof ClassD) {
ClassD x = (ClassD) parameter;
System.out.println(x.logger.getText() + "\n\n");
}
}
}
Logger.java
public class Logger {
private String text = "";
public void setText(String text) {
this.text = text;
}
public String getText() {
return this.text;
}
}
ClassB.java
public class ClassB {
Logger logger = new Logger();
public ClassB() {
logger.setText("Hello from ClassB!");
}
}
ClassC.java
public class ClassC {
Logger logger = new Logger();
public ClassC() {
logger.setText("Hello from ClassC!");
}
}
I'm trying to invoke the getClass() method in order to account for any class with the following, but it's running into some problems.
ClassA.java
public class ClassA {
public static void main(String[] args) {
ClassA classA = new ClassA();
classA.execute();
}
public void execute() {
ClassB doSomething = new ClassB();
writeText(doSomething);
ClassC doSomethingElse = new Class();
writeText(doSomethingElse);
}
public void writeText(Object parameter) {
Class aClass = parameter.getClass();
// now what? The following doesn't work as expected
aClass x = (aClass) parameter;
System.out.println(x.logger.getText());
}
}
No, what you are trying to do will not work. Variable types need to be declared with a known type at compile time.
Use proper encapsulation.
Define an interface HasLogger (or whatever name fits best) which defines a method getLogger that returns a Logger value. Make your classes ClassA, ClassB, etc. implement this interface.
Change your writeText method to accept an argument of type Loggable and then just get the Logger
public void writeText(HasLogger parameter) {
System.out.println(parameter.getLogger().getText());
}
Yes, it is possible to do it with reflection. You might iterate the fields and then call your method on a Logger field. Something like,
public void writeText(Object parameter) {
Class<?> aClass = parameter.getClass();
for (Field f : aClass.getDeclaredFields()) {
if (f.getName().equals("logger")) {
try {
f.setAccessible(true);
Logger log = (Logger) f.get(parameter);
System.out.println(log.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

Confusion with generics, java

I have generic class :
public class Test<T> {
private Test<? extends T> myInstance;
public Test<? extends T> getInstance () {
return myInstance;
}
public void setInstance (Test<? extends T> argType) {
this.myInstance = argType;
}
}
And I have two classes in my class hierarchy relations:
public abstract class Alphabet {
//code here
}
and
public class A extends Alphabet{
public A() {
super();
System.out.print("This is A call");
}
}
Finally I have a class where I want to store make generic class Test with particular type and set new Instance of Object -> A through setInstance() method:
public static void main(String[] args) {
List<Alphabet> list = new ArrayList<Alphabet>();
Test<Alphabet> tAlphabet = new Test<Alphabet>();
tAlphabet.setInstance(new A()); //Here is compilation ERROR
}
But I have got the compilation error in line tAlphabet.setInstance(new A());
What is the issue with my generic class?
Your instance is a Test object as it's currently written, and you are supplying it with an Alphabet object instead. You probably want your instance to be of type Alphabet:
public class Test<T> {
private T myInstance;
public T getInstance() {
return myInstance;
}
public void setInstance(T argType) {
myInstance = argType;
}
}
This way, your Test stores an Alphabet instead of another Test.
It seems you have made things more complicated than needed. You probably want this in your Test class instead of what you actually have:
private T myInstance;
public T getInstance () {
return myInstance;
}
public void setInstance (T argType) {
this.myInstance = argType;
}
With this arrangement you would be free to setInstance(new A()) on a Test<Alphabet> instance.

Innerclass sharing attribute information

I have a class called ContentStream... the problem is that the inner class AddRectancle suppose to get the info of the getter of the class GraphicBeginn...I thought the class ContentStream can reach the getter at least as the getter is public ... plse tell me how to
public class ContentStreamExt extends ContentStreamProcessor
{
private Matrix graphicalMatrix;
public ContentStreamProcessorExt(ExtListener extListener)
{
super(extListener);
}
private void enhanceAdditional()
{
GraphicBeginn beginnGraphic = new GraphicBeginn();
super.register("a", beginnGraphic);
super.register("b", new AddRectangle(beginnGraphic));
}
private static class AddRectangle(GrapicBeginn beginn)
{
// should get the info of uUx and uUy
}
private static class GraphicBeginn implements ContentOperator
{
private float uUx;
private float uUy;
public float getuUx()
{
return this.uUx;
}
public float getuUy()
{
return this.uUy;
}
..... // the input for uUx and uuy will be created in a method
}
The code you gave has a number of problems, it doesn't compile correctly as another poster has noted. It also appears you are providing a method signature while also declaring a class called "AddRectange". Is this a class or a method? You need to decide which, it can't be both. Here is an example that I think illustrates what you're trying to do in a general sense:
public class SampleClass {
public SampleClass() {
}
private void sampleClassMethod() {
A a = new A();
a.acceptB(new B());
}
private class A {
public void acceptB(B bObject) {
System.out.println(bObject.memberVar1);
}
}
private class B {
private int memberVar1 = 5;
}
}
If i understand your question correctly, The add rectangle class should be passed an instance of graphic begin on which it can invoke the public getters. This wiring can be done by the content stream class.
By the way the following is syntactically invalid
private static class AddRectangle(GrapicBeginn beginn)

Good way to implement a child class

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

Categories