How do I create two or more classes that interact with each other?
For example, a method in the first class will be static, producing a Fibonacci number for instance, and another method in the second class will do something with the Fibonacci number which has been created by the method in first class, and how do I extend my classes?
How do I create two or more classes that interact with each other? For
Share
Since it seems that you are beginning to code in java, I’d say that this oracle article about Modifiers are a good start to understand how a Class can interact with another.
So to answer your questions:
There are several ways for one class to interact with another one. Please be aware that I’ve selected the ones I’ve found more useful for your particular example. The most common of them are
Instance of Class Bar call a method from another instance of a Class Foo like the example below:
Class Foo extends Class Bar and call a construct defined on it’s super class: This tries to answer your question on: How you extend a Class
Class Foo expect an instance of Class Bar as an argument of a method:
Going further on your question:
The following example is one way of doing this:
FirstClass.java
SecondClass.java
Example of usage
I hope it helped. Cheers.