2

This is a very basic question, but I'd quite like an explanation of why my question can or cannot be achieved.

If I have a class (A) which contains say a string, with a set method for that string. And I instantiate another class (B) from the first class (A), why can't I then access the first class (A) from the new class (B) to call the set method for the string in the first class (A).

The only reason I ask is that I'm working on a project with a similar problem, from a main class I create a new class which returns some buttons. And when a button is clicked the ActionListener in the main class is supposed to change the String in the initial class, but I cannot seem to access the set Method of the original class without re-instantiating the class.

Sorry if that sounds rambled, but I really want to understand why this is an issue, and what the correct way of doing it is. I know I'll probably be shot down on this, but any help is appreciated.

mino
  • 6,978
  • 21
  • 62
  • 75

4 Answers4

2

Because class B needs to hold a reference of the instance of A from which it has been created. There is no formal reason for which this should be made by default. For example:

public class B {

    private final A creator; 

    public B(A creator) {
        // you might want to check for non null A
        this.creator = creator;
    }

    public void foo(String value) {
        creator.setText(value);
    }
}
Alessandro Santini
  • 1,943
  • 13
  • 17
  • I tried your solution but I got the error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException. I don't understand why I am receiving this error message, can you help? – mino Feb 16 '12 at 21:56
1

Don't know if its the most elegant solution, but if you want object of class B to have a reference to object of class A (the creator) you can use Alessandro example code for class(B) and something like this in class A:

public class A
{
    private String text;

    public void createB()
    {
        new B(this);
    }

    public void setText(String b)
    {
        text = b;
    }
}
Martin
  • 1,130
  • 10
  • 14
0

Class cannot be called unless its been referenced by an Object. So you have to create something like this in Class B

myobject = FirstClass.new  //I am not sure about java syntax as its been many years.

then you can call all the methods of FirstClass on this object and use them in SecondClass.

uday
  • 8,544
  • 4
  • 30
  • 54
0

If B extends A, you can invoke the public methods in B that pertain to A.

If B doesn't extend A, it has no knowledge of A's methods. This is just how Java's inheritance works.

Zack Macomber
  • 6,682
  • 14
  • 57
  • 104