Reputation: 1622
I'm trying to use and learn the composition's relation between classes respecting the flexibility of OOP programming, a small sample code that explains what I'm trying to do:
Main class:
public class MainFrame extends JFrame {
private Test test;
public static void main(String[] args) {
new MainFrame();
}
public MainFrame() {
initFrame();
}
private void initFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(100,100);
setResizable(false);
setUndecorated(true);
setVisible(true);
setLocationRelativeTo(null);
test.update();
}
public void setNumber(int i) {
System.out.println(i);
}
}
and this class:
public class Test {
MainFrame mainFrame;
public void update(){
mainFrame.setNumber(10);
}
}
if i run this i will get :
Exception in thread "main" java.lang.NullPointerException
how can I change the code so that:
The Test
class refers only to the MainFrame
instance created in the main
, not to create a new instance of the MainFrame
inside the Test
class
It is possible to avoid the use of static classes and static functions to do this?
Upvotes: 2
Views: 152
Reputation: 308998
The Test class refers only to the MainFrame instance created in the main, not to create a new instance of the MainFrame inside the Test class
Sorry, this makes no sense. That's not how Java works, and the runtime is educating you.
This code is wrong from top to bottom.
The instance in the Test
class is null because you never initialized it.
The Test
class knows nothing about the main method in the MainFrame
class, nor should it.
The instance in that main method goes out of scope as soon as the method exits and is garbage collected.
Why would the MainFrame class have a reference to a Test instance inside it? Bad design. It's called a circular dependency. Once you add it, you can never separate the two classes. Sometimes they can't be helped, but I see no reason for it at all here, especially for a class named Test
. Test
can know about MainFrame
, but MainFrame
need never know about Test
. You've done it wrong.
You don't need to extend JFrame
. You aren't adding anything by extending. I'll bet this should be a JPanel
that you'll add to a JFrame
.
Upvotes: 2
Reputation: 7057
In stead of advising about design, I'll just put a way to achieve it.
public class MainFrame extends JFrame {
private Test test;
public void setTest(Test test) {
this.test = test;
}
}
and
public class Test {
MainFrame mainFrame;
public Test(MainFrame mainFrame) {
this.mainFrame = mainFrame;
this.mainFrame.setTest(this);
}
}
Good luck.
Upvotes: 2
Reputation: 15758
Quick fix for your NullPointerExceptions:
public class Test {
MainFrame mainFrame;
public void update(){
mainFrame.setNumber(10);
}
public void setMainFrame(MainFrame mainFrame) {
this.mainFrame = maninFrame;
}
In initFrame()
:
test = new Test();
test.setMainFrame(this);
test.update();
Otherwise I agree, the concept you're trying has a lot of misunderstanding. Try to separate the Test
and MainFrame
logic.
Upvotes: 1