[Solved] Cannot access an Object Reference instantiated by a sibling class


So, blah defines an instance field called label but does not initialise it

public abstract class Blah 
{
    protected JLabel label;
}

BlahChildOne initialises the label from Blah

public class BlahChildOne extends Blah
{
    public BlahChildOne()
    {
        label = new JLabel();
    }
}

BlahChildTwo does not initialises the label from Blah, so it is still null

public class BlahChildTwo extends Blah
{
    public BlahChildTwo()
    {
        label.setText("Fred");
    }
}

Neither BlahChildOne or BlahChildTwo share information between them (they have commonality through inheritance from Blah, but the actually information is each owns).

Think of it like identical twins, they might share commonality, but just because one get’s sick, doesn’t mean the other will, they are their own self contained instance.

IF you want to share information between classes, you should consider providing a reference to the class with the information you want to share, for example…

public class BlahChildTwo extends Blah
{
    public BlahChildTwo(Blah blah)
    {
        label = blah.label;
        label.setText("Fred");
    }
}

But I’d really like to see a use case for something so drastic…

Why static is consider bad

Lets assume…

public abstract class Blah 
{
    protected static JLabel label;
}

Now in your code, you do something like…

BlahChildOne bco = new BlahChildOne();
add(bco.label); // It the label to the screen...
BlahChildTwo bct = new BlahChildTwo();

Okay, so far, so good. Now imagine, somewhere else in your code, you do…

BlahChildOne bco = new BlahChildOne();
BlahChildTwo bct = new BlahChildTwo();

…But why hasn’t the screen updated? Because Blah#label is no longer pointing to the JLabel which you previously added to the screen, you’ve lost that reference.

This is pain in the debugger to find, even when you know what you are looking for, because there is no accountability, any class that extends Blah can create a new instance of JLabel and assign it to label.

3

solved Cannot access an Object Reference instantiated by a sibling class