[5887] in java-interest
Re: Static variable assigment
daemon@ATHENA.MIT.EDU (trk@bilbo.wipsys.soft.net)
Sat Mar 2 00:16:42 1996
From: trk@bilbo.wipsys.soft.net
To: vitaly@diogen.asc.rssi.ru (Vitaly Promislov)
Date: Sat, 2 Mar 1996 09:28:51 -0500 (GMT)
Cc: java-interest@java.sun.com (jig)
In-Reply-To: <9603011158.AA28686@diogen.asc.rssi.ru> from "Vitaly Promislov" at Mar 1, 96 02:58:32 pm
Vitaly Promislov writes:
> class Connect extends Applet
> {
> private final static int DEFAULT_PORT=4321;
> private int server_port=DEFAULT_PORT;
>
> public static void main(String args[])
> {
> try
> {
> server_port = (int)Integer.parseInt(args[0]);
> // <<<< Error is here (line 67) !!!!
> }
> catch(Exception e)
> {
> System.out.println("Defaulting to port " + DEFAULT_PORT);
> }
> new Connect();
>
> Connect.java:67: Can't make a static reference to nonstatic variable server_port in class GenericServer.
> server_port = (int)Integer.parseInt(args[0]);
>
You should not access any non-static variable from within the main() member
function, which is a static.
A static variable of a class will be the same for all the objects of that class,
whereas a non-static variable will be different for the different objects of the
class ( am I stating the obvious?)
In such a case, if you modify a non-static member ( server_port in your code)
from a static method, the operation is ambiguous. This is because, you are
trying to modify a variable which is DEFINED (memory allocated etc.)
only in an object of that class.
Typically, in main(), one calls the constructor of the same class to create
that object and and then call the methods on that object.. Looking at your
code, I feel, you should have a local variable in the main function
to which you assign the result of parseInt() and then you should pass
it on to the constructor as a parameter. This constructor, would in turn
set-up that variable server_port..
Cheers
TRK
--
_________________________________________________________________
T. Rama Kumar ph: 91-80-2210818
Wipro Systems e-mail: trk@bilbo.wipsys.soft.net
40/1A,Lavelle Road
Bangalore
India
-----------------------------------------------------------------
Life is too important to be taken seriously.
_________________________________________________________________
-
This message was sent to the java-interest mailing list
Info: send 'help' to java-interest-request@java.sun.com