Private,public and static variable
I am just not able to understand the use of declaring the variable as private.Because even if i declare the variable as public ,other user of the same application anyway will never be acess that variable !! Can someone clear my doubt.
Also can some one tell me when can I declare a variable as static...that is ideallly when should i declare a variable as static (and for that matter private and public )
Thanks.
Tha
Hi,
There are some rules for variable declarations:
Only the containing class and its inner classes can access private variables.
Every class can access public variables.
All classes in the same package can access protected variables.
Imagine you're writing a program for archiving all your CD's.
If you want to know how many cd's you have got you simply read the static variable.
public class CD {
private String name, author;
public static int cdCount = 0;
public CD(String name, String author){
//do something to initialize
cdCount++; //Increase the value, because a new CD has been created.
public static int getCDCount(){ //static methods can be accessed without creating instances of classes
return cdCount;
public static void main(String[] args){
CD kravitz = new CD("Lenny Kravitz", "A Song");
CD britney = new CD("Britney Spears", "Another Song");
System.out.println("You have " CD.getCDCount() " CDs"); //You call static methods on the class (you can also call them on instances, but it is important that you do not need to create a object of that class)
}
Similar Messages
-
Hi all,
does anyone know how to define/use static variables inside a BPEL process? Or, is there any way so I can keep data from a (synchroneous) invocation to be used during the next (synchroneous) invocation?
thanks for your help, I have been working on this for many many days !
Abdel.How about a BPEL process that maintains your static variables and uses a custom correlation token. Queries to the process can retrieve the variable requested, and if they use the custom correlation token then the process will act as a singleton.
I suggest using event processing rather than simple receive to handle the messages. -
Java, toString() and static variables
http://paste.opsat.net/?/120/ is the assignment, and
http://paste.opsat.net/?/121/ is the java i wrote for it.
After comparing my program to the assignment you'll notice there's no StudentGrade class, or a toString method. How would i design a program using a second class and a toString method to do the same thing this one does?
TIA
--mkhttp://paste.opsat.net/?/124/ is my new java code.
i guess i could even eliminate the toString method by changing my println statement to something like:
System.out.println(stu_i.name + "\t" + stu_i.grade);
"by passing the data to the Student contructor during instantiation, it will save you a lot of code calling setter methods to do the same..."
seems to be the understatement of the day, that SAVES A LOT OF TYPING.
Ill talk to my classmates tomorrow and see if i cant drag any insight out of them about if i should leave my code like this or if i should re-add the calculategrade method or not.
thanks a bunch
--mk -
Why is that Java does not allow the declaration of a variable in a method, which may be static method or a non-static method to be a static variable? Is there any specific reason for that ....????
The other thing is that if i declare a constructor as a private member in the class so as to restrict the number of objects which can be created. But if i do write is the main in the same class then i can straigthaway can create the objects as if the constructor is public.i.e. i can use is the new operator.......if the same if i have a containment kind of instantion then it says that it cannot access the private member in which i write is a factory method. Why so ? why is the main able to access the private members of the class.....by this we say the idea of encapsulation is being voilated.......
Regds,
JayWhy is that Java does not allow the declaration of a
variable in a method, which may be static method ora
non-static method to be a static variable? Is there
any specific reason for that ....????
methods are either static or non-static therefore
method variables of a static method are intrinsically
static just as members of a private method (putting
aside the scope of the method for a moment) are
intrinsically private. Why on earth would you want to
make a method variable specifically static?
This makes no sense.members of a private method are not public or private or anything. Well this could be explained better in terms of closure. Closures relate to the life-time of local variables (and parameters). In Java, any time a method is called, a new set of the method's local variables (and parameters) are allocated upon the stack. For Java, an environment is typically implemented as a stack allocated activation record. When a method returns, the environment associated with the current activation is discarded. This is why you can have multiple activation of a method (for example a recursive method) and each activation has its own private set of local variables.
>
>
The other thing is that if i declare a constructoras
a private member in the class so as to restrict the
number of objects which can be created. But if i do
write is the main in the same class then i can
straigthaway can create the objects as if the
constructor is public.i.e. i can use is the new
operatorI presume you mean main() method signature which must
be public and static. Well ...Main method signature is always public and static except if you are talking about the bug until java 1.4
1. We'd all be a bit stuffed if it wasn't
2. The private class constructor is only visible from
the class where the access modifier is declared, this
isn't to say that the constructor is public at all as
it is inaccessible from outside other than the system
call to java, jar, jajaw or whateverThe accessor private doesnot limit the access to the members of the class in question. And the reason you would like to implement something like a singleton wouldnot be from within the same class definition but from other classes.
>
>
.......if the same if i have a containment
kind of instantion then it says that it cannotaccess
the private member in which i write is a factory
method. Why so ?I assume because you made it private, that is what you
asked for, the method is hidden and not accessible
outside the class. This is encapsulation.
why is the main able to access the
private members of the class.....by this we say the
idea of encapsulation is being voilated.......
No, not at all as it is only accessible from main
which merely launches the program.
I think you need to answer for yourself a question
asked in this forum just a few days ago ===> why is
main() static and public and void?And I would also suggest going through the factory patterns once again. -
Instance initializer and static initializer blocks
Hi guys,
I read about the above mentioned in the JLS and also in a book before, but I still don't quite understand, what is the use of these. I sort of have a rough idea, but not exactly. I mean, what is the purpose of the instance initializer and static initializer blocks, how can it be useful? I understand I can execute pieces of code that will initialize instance and static variables accordingly, but how is it different then to using a constructor to initialize these fields? Are these pieces of code executed before any constructor is executed, or when otherwise?
Sorry for my noob, I'm learning.
PR.Static initializers are useful for initializing a class when the initialization is more complex than simply setting a single variable, or when that initialization can throw a checked exception.
public class Foo {
private static final Bar bar;
static {
try {
bar = new Bar();
bar.doSomeInitializationStuff();
catch (SomeCheckedExceptionThatBarThrows e) {
throw new ExceptionInInitializerError(e);
}Here we could not do the two-step new Bar() + doSomeInit() stuff in the line where we declare the bar variable. Additionally, assuming that one or both of those can throw a checked exception, we could not do that on the declaration line; we need the static initializer to wrap that in the appropriate unchecked exception.
This allows us to do more complex class initialization when the class is loaded than we could do with a simple variable initialization.
Instance initializers are useful if you want to perform the same steps in every constructor and don't want to have to repeat the code in each constructor. Instance initializers are executed as the first step of each constructor (or maybe it's after any super() calls, I forget). -
How to javadoc "public final static int"?
How can we create "Field Summary" HTML document for "public final static int" variables?
This question is probably same as the below question.
http://forums.java.sun.com/thread.jsp?forum=41&thread=72832
p.s.
The below document indicates CENTER, NORTH, ...
How an we achieve it to document "public final static" variables?
http://java.sun.com/products/jdk/1.2/docs/api/index.htmlNo, 1.3 does not have the static constant values exposed to the Doclet API,
and so that information is not available to any doclets to place in the
generated documentation.
BTW, based on feedback from a developer, we changed the format from:
public static final int NORTH = 0
to
public static final int NORTH
See: Constant values
where the "Constant values" link takes them to a summary page that
lists all of the values. This helps discourage users from mistakenly
seeing and using the value instead of the constant.
-Doug Kramer
Javadoc team -
Problem with local class, static private attribute and public method
Hello SDN,
Consider the following situation:
1) I have defined a LOCAL class airplane.
2) This class has a private static attribute "type table of ref to" airplane (array of airplanes)
3) A public method should return the private static table attribute
Problems:
a) The table cannot be given as an EXPORTING parameter in the method because TYPE TABLE OF... is not supported and I get syntax errors. I also cannot define a dictionary table type because it is a local class.
b) The table cannot be given as a TABLES parameter in the method because TABLES is not supported in the OO context.
c) The table cannot be given as an EXPORTING parameter in the method defined as LIKE myStaticAttribute because my method is PUBLIC and my attribute is PRIVATE. ABAP syntax requires that all PUBLIC statements are defined before PRIVATE ones, therefore it cannot find the attribute to reference to with LIKE.
I see only 2 solutions:
a) Never ever use local classes and always use global classes so that I might define a dictionary table type of my class which I can then use in my class.
b) Make the attribute public, but this goes against OO principles, and isn't really an option.
Am I missing anything here, or is this simply overlooked so far?Hello Niels
Since your class is local and, thus, only know to the "surrounding" application is does not really make sense to make it public to any other application.
However, if you require to store instances of your local classes in internal tables simply use the most generic reference type possible, i.e. <b>OBJECT</b>.
The following sample report shows how to do that. Furthermore, I believe it also shows that there are <u><b>no </b></u>serious inconsistency in the ABAP language.
*& Report ZUS_SDN_LOCAL_CLASS
REPORT zus_sdn_local_class.
" NOTE: SWF_UTL_OBJECT_TAB is a table type having reference type OBJECT
* CLASS lcl_airplane DEFINITION
CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
DATA: md_counter(3) TYPE n.
METHODS: constructor,
get_instances
RETURNING
value(rt_instances) TYPE swf_utl_object_tab.
PRIVATE SECTION.
CLASS-DATA: mt_instances TYPE swf_utl_object_tab.
ENDCLASS. "lcl_airplane DEFINITION
* CLASS lcl_airplane IMPLEMENTATION
CLASS lcl_airplane IMPLEMENTATION.
METHOD constructor.
APPEND me TO mt_instances.
DESCRIBE TABLE mt_instances.
md_counter = syst-tfill.
ENDMETHOD. "constructor
METHOD get_instances.
rt_instances = mt_instances.
ENDMETHOD. "get_instance
ENDCLASS. "lcl_airplane IMPLEMENTATION
DATA:
gt_instances TYPE swf_utl_object_tab,
go_object TYPE REF TO object,
go_airplane TYPE REF TO lcl_airplane.
START-OF-SELECTION.
" Create a few airplane instance
DO 5 TIMES.
CREATE OBJECT go_airplane.
ENDDO.
gt_instances = go_airplane->get_instances( ).
CLEAR: go_airplane.
LOOP AT gt_instances INTO go_object.
go_airplane ?= go_object.
WRITE: / 'Airplane =', go_airplane->md_counter.
ENDLOOP.
END-OF-SELECTION.
Regards
Uwe<u></u> -
Discussion: private final static vs public final static
take following class variable:public final static int constant = 1;Is there any harm in making this variable public if it's not used (and never will be) in any other class?
Under the same assumption Is there any point in making this variable static?
tx for your inputIs there any harm in making this variablepublic
if it's not used (and never will
be) in any other class?Harm? No. Use? Neither.I suppose it makes no difference at all concerning
runtime performance?
Under the same assumption Is there any point inmaking this variable
static?If the creation of the constant is costly, for
instance. A logger is private final static most of
the time.Same here, does making a variable final or static
have any influence on runtime performance?No. And for 'expensive' operations (say, parsing a XML configuration file, which only needs to occur once), making a variable static will improve performance.
- Saish -
(JC) static variable and derived object
Hi there!
It is glad to know you from Java Card Forum. Can I ask for your help on the following question?
It is about static variable. The following is my sample code:
========================================
package com.Test01;
import javacard.framework.*;
import javacard.security.*;
import javacardx.crypto.Cipher;
public class Test01 extends Applet {
OwnerPIN Pin;
static DESKey[] keys;
protected Test01(byte[] buffer, short offset, byte length) {
keys = new DESKey[4];
length = 0;
while (length < 4) {
keys[length] = (DESKey)KeyBuilder.buildKey((byte)3, (short)0x80, false);
length = (byte)(length + 1);
public static void install(byte buffer[], short offset, byte length) {
new Test01(buffer, offset, length);
===========================================================
If there are two instances, A and B, created in the package.
My issues:
1. Are keys[0]~ keys [3] kept while B is deleted?
2. Does each instance have itsown object while "keys[length] = (DESKey)KeyBuilder.buildKey((byte)3, (short)0x80, false);"? or they share the same object?
3. follow item 2, if A and B share the same object, is the object kept while B is deleted? Where can I get the information in Sun's spec?
Thank you very much.
Best regards,
kantieThanks a lot. You mean that keys variable will be removed while instance B deleted, right? I think the idea of database applet is very good, but I can't force applet provider the way of their implementations : )
I still got question, does it get no use to set the keys variable to be "static"? So that I can keep it to other instances, if applied.
And I think that any object derived under the static variable shall be kept, until the package is deleted.
For example, if you declare a static pointer, and it points to an object newed by the instance at the first time. We say every instances (A and B) of this package (PckM) share this same static pointer and this same object, right? There are two situations:
1. if this referred object is removed when B is deleted, so the memory of this object will be released. Then user might create an instace C of another package (PckN), and instance C new its objects just overlapping on the released memory. In this case, it will cause instance A to be crashed, because its static pointer has been referred to illeagle address.
2. if this referred object is kept when B is deleted, then instance C will new its objects in other free memory. In this case, instance A will work well, because its static pointer still refers to correct object.
What do you think? Am I missing any concepts?
Thank you for your great opinions.
Best regards,
kantie -
Static and non-static variables and methods
Hi all,
There's an excellent thread that outlines very clearly the differences between static and non-static:
http://forum.java.sun.com/thread.jsp?forum=54&thread=374018
But I have to admit, that it still hasn't helped me solve my problem. There's obviously something I haven't yet grasped and if anyone could make it clear to me I would be most grateful.
Bascially, I've got a servlet that instatiates a message system (ie starts it running), or, according to the action passed to it from the form, stops the message system, queries its status (ie finds out if its actually running or not) and, from time to time, writes the message system's progress to the browser.
My skeleton code then looks like this:
public class IMS extends HttpServlet
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
doPost(request, response);
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
//get the various parameters...
if (user.equalsIgnoreCase(username) && pass.equalsIgnoreCase(password))
if(action.equalsIgnoreCase("start"))
try
IMSRequest imsRequest = new IMSRequest();
imsRequest.startIMS(response);
catch(IOException ex)
catch(ClassNotFoundException ex)
else if(action.equalsIgnoreCase("stop"))
try
StopIMS stopIMS = new StopIMS();
stopIMS.stop(response);
catch(IOException ex)
else if(action.equalsIgnoreCase("status"))
try
ViewStatus status = new ViewStatus();
status.view(response);
catch(IOException ex)
else
response.sendRedirect ("/IMS/wrongPassword.html");
public class IMSRequest
//a whole load of other variables
public PrintWriter out;
public int messageNumber;
public int n;
public boolean status = false; //surely this is a static variable?
public String messageData = ""; // and perhaps this too?
public IMSRequest()
public void startIMS(HttpServletResponse response) throws IOException, ClassNotFoundException
try
response.setContentType("text/html");
out = response.getWriter();
for(n = 1 ; ; n++ )
getMessageInstance();
File file = new File("/Users/damian/Desktop/Test/stop_IMS");
if (n == 1 && file.exists())
file.delete();
else if (file.exists())
throw new ServletException();
try
databaseConnect();
catch (ClassNotFoundException e)
//here I start to get compile problems, saying I can't access non-static methods from inside a static method
out.println(FrontPage.displayHeader());
out.println("</BODY>\n</HTML>");
out.close();
Thread.sleep(1000);
catch (Exception e)
}OK, so, specifially, my problem is this:
Do I assume that when I instantiate the object imsRequest thus;
IMSRequest imsRequest = new IMSRequest();
imsRequest.startIMS(response); I am no longer in a static method? That's what I thought. But the problem is that, in the class, IMSRequest I start to get compile problems saying that I can't access non-static variables from a static method, and so on and so on.
I know I can cheat by changing these to static variables, but there are some specific variables that just shouldn't be static. It seems that something has escaped me. Can anyone point out what it is?
Many thanks for your time and I will gladly post more code/explain my problem in more detail, if it helps you to explain it to me.
DamianCan I just ask you one more question though?Okay, but I warn you: it's 1:00 a.m., I've been doing almost nothing but Java for about 18 hours, and I don't do servlets, so don't take any of this as gospel.
If, however, from another class (FrontPage for
example), I call ((new.IMSRequest().writeHTML) or
something like that, then I'm creating a new instance
of IMSRequest (right?)That's what new does, yes.
and therefore I am never going
to see the information I need from my original
IMSRequest instance. Am I right on this?I don't know. That's up to you. What do you do with the existing IMS request when you create the new FrontPage? Is there another reference to it somewhere? I don't know enough about your design or the goal of your software to really answer.
On the other hand, IMSRequest is designed to run
continuously (prehaps for hours), so I don't really
want to just print out a continuous stream of stuff to
the browser. How can I though, every so often, call
the status of this instance of this servlet?One possibility is to pass the existing IMSRequest to the FrontPage and have it use that one, rather than creating its own. Or is that not what you're asking? Again, I don't have enough details (or maybe just not enough functioning brain cells) to see how it all fits together.
One thing that puzzles me here: It seems to me that FP uses IMSReq, but IMSReq also uses FP. Is that the case? Those two way dependencies can make things ugly in a hurry, and are often a sign of bad design. It may be perfectly valid for what you're doing, but you may want to look at it closely and see if there's a better way. -
Static variable and non-static
I have a quick question. The following syntax compiles.
private String t = key;
private static String key = "key";
But this doesn't compile.
private String t = key;
private String key = "key";
Can anybody explain how it is treated in java compiler?
Thanks.jverd wrote:
doremifasollatido wrote:
I understand that completely. I didn't say that the OP's version with static didn't work. I was just giving an alternative to show that you don't need static, if you change the order that the instance variables are declared.My problem with the underlined is that, while technically true, I can see where a newbie would take it as "oh, so that's how I can get rid of static," and focus only on how to satisfy the compiler, rather than on learning a) when it's appropriate to make something static or not from a design perspective, and b) what the implications of that decision are, for both static and non.
I have just a wee bit of a prejudice against the "what do I type to make the error messages go away" approach. :-)That sounds good to me. We're currently trying to fix an issue caused by the fact that one class has most of its variables as static, when they should really be instance variables. There should only be one active instance of this class at a time, but the values of the static variables stick around when you call "new ThisClass()". So, old data interferes with new data, and various errors happen. The class has many static methods to access the static variables, but it should have been more of a Singleton--an actual object with non-static variables. The active instance of the Singleton would need to be replaced at logout/login (as opposed to shutdown completely and restart the JVM), but then at least when the new instance were created, then all of the variables would be initialized to empty--the old instance would disappear. The solution at the moment (solution by others--I don't agree) is to clear each static Vector and then set the reference to null (setting to null would be enough to drop the old data, but certain people don't get that...). This is fragile because many variables were missed in this "cleanup" process, and it will be easy to forget to "cleanup" new variables in the future. This class has been misdesigned for years (much longer than I've been here). The calls to static methods permeate the application, so it isn't easy to fix it quickly. There are several of these misdesigned classes in our application--a mix of static and non-static, when nothing or almost nothing should be static. -
Difference between public void, private void and public string
Hi everyone,
My 1st question is how do you know when to use public void, private void and public string? I am mightily cofuse with this.
2ndly, Can anybody explain to me on following code snippet:
Traceback B0;//the starting point of Traceback
// Traceback objects
abstract class Traceback {
int i, j; // absolute coordinates
// Traceback2 objects for simple gap costs
class Traceback2 extends Traceback {
public Traceback2(int i, int j)
{ this.i = i; this.j = j; }
}And using the code above is the following allowed:
B[0] = new Traceback2(i-1, 0);
Any replies much appreciated. Thank you.1)
public and private are access modifiers,
void and String return type declarations.
2)
It's called "inheritance", and "bad design" as well.
You should read the tutorials, you know? -
Viewing document characteristics in Easy DMS public and private folders
We have classified our documents in SAP Document Management System. We are viewing the DIRs in Easy DMS. In the public and private folders, the classification characteristics columns can be added to the screen report, however the values for the characteristics do not appear in the columns. If we use the search function and view those same documents in the search screen, the characteristic values do appear. How can we get these values to appear in the public and private folder views? There does not seem to be an OSS notes which address this discrepancy. In advance, any assistance is most appreciated.
Hi Barry - As Daniel explained, sometimes system behaves if the Default box is not checked but I want you to check the EasyDMS version/patch you are using. Below is the screenshot of latest version/patch.
If you have old verison/patch, please implement the latest version/patch and check.
/Tilak -
Hi there,
I am looking for step by step instrcutions on how to configure SFTP Codeplex adapter for both receive and send ports.
Out business partner with whom we push/poll the files from wants us to use SSH encryption/decryption etc.
Just wondering if the following functionality is supported in Codeplex SFTP adatper without having to write any code.
Appreciate if there is manaul to do this for SFTP. BTW I do have all the our public and private keys and business partners Public key for configuring.
For Send port: 1. we would need to encrypt the file with our business partners public key
2. sign the file with our private key.
3. Send the file through to SSH client which eventually transfers to Remote server.
Receive port: 1. Connect to SSH Server with SSH-2 key and receive the file
2. Verify the file's digital signature agaisnt the Business partners PGP public key
3. Decrypt the file using our PGP Public key
Thanks in advanceYes it is supported.
You can find its documentation in this link
You can find section X.509 Certificate Identity Keys
You can set public and private key in property SSH Identity thumbprint of send and receive port
I prefer to test it using client tool like
FileZilla or WinSCP then test it using sftp adapter
When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer -
When should I use static variable and when should not? Java essential
When should I use static variable and when should not? Java essential
Static => same value for all instances of the class.
Non-static => each instance can have its own value.
Which you need in which circumstances is completely up to you.
Maybe you are looking for
-
How can I entirely disable language proofing from iPad??
I cannot use iPad to write in different languages, because of the annoyance of being continously "suggested" the "correct" italian (my native language) spelling. Since this happens in every app where keybord can be invoked, the only solution appear n
-
please anybody tell me the functionality of these classes.it will be better if u give a brief. CL_GUI_CUSTOM_CONTAINER , CL_GUI_ALV_GRID , CL_GUI_ALV_GRID , CL_GUI_DIALOGBOX_CONTAINER .
-
SQL FUNCTION to compute MEDIAN
Hi Just as we use MAX and MIN to compute the maximum and minimum values using SELECT query in SQL, does anyone know of a direct/indirect function/method to calculate the MEDIAN of a given set of values. Powerbuilder provides median function. I am loo
-
Unable to launch Photoshop Elements Editor 8
Ok so I just downloaded the trial version of this program hoping to get a good look at what 80 bucks would buy me. I can look at photos in the Organizer, but as soon as I try and open the Editor, Windows tells me it has stopped responding and ias loo
-
Adobe flash player will not update
Adobe Flash Player is asking me to update when I do it only goes to step 2 of 3 then it dies please help