Hey,

I have one class Company and one Item class which is an object in Company class as shown:

public abstract class Company {

    @Inject
    private ItemClass item;

    void companyMethod() {
           this.item.itemMethod();
    }
}

public class ItemClass {
    public void itemMethod() {
       // logic
    }
}

So, many class inherits the Company abstract class say ClassA, ClassB, ClassC. So,

public class ClassA extends CompanyClass {

    void ClassAMethod() {
    }

    String getName() {
        //logic
    }
}

So, now when I declare a variable of ClassA say: classAObj . I called:

classAObj.companyMethod()

Now, I want to call ClassA's getName function in ItemMethod() of item class. Can i use this somehow? I need to call getName() there and take string value from this function? Using this or similar somehow?

Thanks in advance.

I'm not sure I understand what you are asking, but to call the getName instance method of the ClassA class you will need an instance of ClassA, as in
String s = classAObj.getName();

Hi,

Thanks for the response, James. No. I have to call getItem() method of ClassA class like this:

classAObj.companyMethod()

I will call company method as ClassA is inherited class of Company class. So, now, company method will call this.item.itemMethod() function. correct? Here comes the point of attraction: I want to call getName() method in itemMethod() method of class Item. I hope I am more clear this time. :)

Main point is: I want to call methods of ClassA class from class item class methods. Like item class obj is there in company class & company class is parent class of ClassA, ClassB etc. I have to take reference of ClassA somehow in functions of item class & then call it.

So, getName() is overriden in classA , ClassB etc so based on the value this fuction will return I have to do some logic in itemMethod() method. I must know who called this item clas obj (it is classA obj or classB or something else).

Thanks in advance.

Edited 8 Months Ago by nitin1

So in itemMethod you need to know the instance of Company (or one of its subclasses) that called it? Unless there's already some data item or structure that holds that info you will need to pass it to itemMethod, as in

public class ItemClass {
    public void itemMethod(Company caller) {
       // logic
       String s = caller.toString();
    }
}

public abstract class Company {
    private ItemClass item;
    void companyMethod() {
         item.itemMethod(this);
    }
}

Assuming that this is what you wanted, I would just say that to me there's a small worry about the design behind this - such tight two-way coupling is best avoided if possible.

This article has been dead for over six months. Start a new discussion instead.