• Post Reply Bookmark Topic Watch Topic
  • New Topic

Using a variable from the Main class in another class  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not very experimented with Java, and that's why I'm asking here.

I have a program with 4 classes, all of them in the same package, one of them is the Main class, and in that class I declared a variable named "port" of type int.

One of the 3 another ones is the class Connection class, which it requires the port variable.

So, my question is the following: I want to use this variable in the Connection class. How can I do it?

Both classes are shown below:

Main.java


Connection.java

 
Bartender
Posts: 1603
232
Android Angular Framework Eclipse IDE Java Linux MySQL Database Redhat TypeScript
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the relationship between Main and Conexion? If Main is responsible for creating an instance of Conexion, then include a constructor for Conexion with a port parameter, and have Main pass the port number in the constructor.

You could also have Conexion reference Main's port value directly, but that requires port to be static. It also has a negative effect of making Conexion dependent on Main.
 
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cristian

Is there a reason why you have declared port in Main and not in Conexion?
 
Ranch Hand
Posts: 355
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Cristian,
Make sure that the basic classes you have provided compile successfully. Then you could move onto the next stage.
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cristian, welcome to the Ranch.

In Java, you cannot declare variables at the global level, as you are doing in line 7 of your code. Variables must always be declared inside a class or method.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!