static
My question is about one particular usage of static keyword. It is possible to use static
keyword to cover a code block within a class which does not belong to any function. For example following code compiles:
public class Test {
private static final int a;
static {
a = 5;
doSomething(a);
}
private static int doSomething(int x) {
return (x+5);
}
}
If you remove the static
keyword it complains because the variable a
is final
. However it is possible to remove both final
and static
keywords and make it compile.
It is confusing for me in both ways. How am I supposed to have a code section that does not belong to any method? How is it possible to invoke it? In general, what is the purpose of this usage? Or better, where can I find documentation about this?
Why doesn't Java allow overriding of static methods?Why is it not possible to override static methods?
If possible, please use an example.
private final static attribute vs private final attributeIn Java, what's the difference between:
private final static int NUMBER = 10;
and
private final int NUMBER = 10;
Both are private
and final
, the difference is the static
attribute.
What's better? And why?
Static Block in JavaI was looking over some code the other day and I came across:
static {
...
}
Coming from C++, I had no idea why that was there. Its not an error because the code compiled fine. What is this "static" block of code?
What is the reason behind "non-static method cannot be referenced from a static context"?The very common beginner mistake is when you try to use a class property "statically" without making an instance of that class. It leaves you with the mentioned error message:
You can either make the non static method static or make an instance of that class to use its properties.
What the reason behind this? Am not concern with the solution, rather the reason.
private java.util.List<String> someMethod(){
/* Some Code */
return someList;
}
public static void main(String[] strArgs){
// The following statement causes the error.
java.util.List<String> someList = someMethod();
}
The static keyword and its various uses in C++
The keyword static
is one which has several meanings in C++ that I find very confusing and I can never bend my mind around how its actually supposed to work.
From what I understand there is static
storage duration, which means that it lasts for the lifetime of the program in the case of a global, but when you're talking about a local, it means that it's zero initialized by default.
The C++ Standard says this for class data members with the keyword static
:
3.7.1 Static storage duration [basic.stc.static]
3 The keyword static can be used to declare a local variable with static storage duration.
4 The keyword static applied to a class data member in a class definition gives the data member static storage duration.
What does it mean with local variable? Is that a function local variable? Because there's also that when you declare a function local as static
that it is only initialized once, the first time it enters this function.
It also only talks about storage duration with regards to class members, what about it being non instance specific, that's also a property of static
no? Or is that storage duration?
Now what about the case with static
and file scope? Are all global variables considered to have static storage duration by default? The following (from section 3.7.1) seems to indicate so:
1 All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program (3.6.2, 3.6.3)
How does static
relate to the linkage of a variable?
This whole static
keyword is downright confusing, can someone clarify the different uses for it English and also tell me when to initialize a static
class member?
I've written a factory to produce java.sql.Connection
objects:
public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory {
@Override public Connection getConnection() {
try {
return DriverManager.getConnection(...);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
I'd like to validate the parameters passed to DriverManager.getConnection
, but I don't know how to mock a static method. I'm using JUnit 4 and Mockito for my test cases. Is there a good way to mock/verify this specific use-case?
If a variable is declared as static
in a function's scope it is only initialized once and retains its value between function calls. What exactly is its lifetime? When do its constructor and destructor get called?
void foo()
{
static string plonk = "When will I die?";
}
Static variables in JavaScript
How can I create static variables in Javascript?
What does "static" mean in C?I've seen the word static
used in different places in C code; is this like a static function/class in C# (where the implementation is shared across objects)?
What is the difference between static and non-static nested class?
New self vs. new staticI am converting a PHP 5.3 library to work on PHP 5.2. The main thing standing in my way is the use of late static binding like return new static($options);
, if I convert this to return new self($options)
will I get the same results?
What is the difference between new self
and new static
?
The question was about plain c functions, not c++ static
methods, as clarified in comments.
I understand what a static
variable is, but what is a static
function?
And why is it that if I declare a function, let's say void print_matrix
, in let's say a.c
(WITHOUT a.h
) and include "a.c"
- I get "print_matrix@@....) already defined in a.obj"
, BUT if I declare it as static void print_matrix
then it compiles?
UPDATE Just to clear things up - I know that including .c
is bad, as many of you pointed out. I just do it to temporarily clear space in main.c
until I have a better idea of how to group all those functions into proper .h
and .c
files. Just a temporary, quick solution.
I'd like to have a private static constant for a class (in this case a shape-factory).
I'd like to have something of the sort.
class A {
private:
static const string RECTANGLE = "rectangle";
}
Unfortunately I get all sorts of error from the C++ (g++) compiler, such as:
ISO C++ forbids initialization of member ‘RECTANGLE’
invalid in-class initialization of static data member of non-integral type ‘std::string’
error: making ‘RECTANGLE’ static
This tells me that this sort of member design is not compliant with the standard. How do you have a private literal constant (or perhaps public) without having to use a #define directive (I want to avoid the uglyness of data globality!)
Any help is appreciated.
What does the 'static' keyword do in a class?To be specific, I was trying this code:
package hello;
public class Hello {
Clock clock = new Clock();
public static void main(String args[]) {
clock.sayTime();
}
}
But it gave the error
Cannot access non-static field in static method main
So I changed the declaration of clock
to this:
static Clock clock = new Clock();
And it worked. What does it mean to put that keyword before the declaration? What exactly will it do and/or restrict in terms of what can be done to that object?
How do you create a static class in C++?How do you create a static class in C++? I should be able to do something like:
cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;
Assuming I created the BitParser
class. What would the BitParser
class definition look like?
The method signature of a Java main
method is:
public static void main(String[] args) {
...
}
Is there a reason why this method must be static?
Difference between static class and singleton pattern?What real (i.e. practical) difference exists between a static class and a singleton pattern?
Both can be invoked without instantiation, both provide only one "Instance" and neither of them is thread-safe. Is there any other difference?
When to use static classes in C#Here's what MSDN has to say under When to Use Static Classes:
static class CompanyInfo { public static string GetCompanyName() { return "CompanyName"; } public static string GetCompanyAddress() { return "CompanyAddress"; } //... }
Use a static class as a unit of organization for methods not associated with particular objects. Also, a static class can make your implementation simpler and faster because you do not have to create an object in order to call its methods. It is useful to organize the methods inside the class in a meaningful way, such as the methods of the Math class in the System namespace.
To me, that example doesn't seem to cover very many possible usage scenarios for static classes. In the past I've used static classes for stateless suites of related functions, but that's about it. So, under what circumstances should (and shouldn't) a class be declared static?
Can I add extension methods to an existing static class?I'm a fan of extension methods in C#, but haven't had any success adding an extension method to a static class, such as Console
.
For example, if I want to add an extension to Console
, called 'WriteBlueLine
', so that I can go:
Console.WriteBlueLine("This text is blue");
I tried this by adding a local, public static method, with Console
as a 'this
' parameter... but no dice!
public static class Helpers {
public static void WriteBlueLine(this Console c, string text)
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine(text);
Console.ResetColor();
}
}
This didn't add a 'WriteBlueLine
' method to Console
... am I doing it wrong? Or asking for the impossible?
I have a class with a private static final
field that, unfortunately, I need to change it at run-time.
Using reflection I get this error: java.lang.IllegalAccessException: Can not set static final boolean field
Is there any way to change the value?
Field hack = WarpTransform2D.class.getDeclaredField("USE_HACK");
hack.setAccessible(true);
hack.set(null, true);
Static vs class functions/variables in Swift classes?
The following code compiles in Swift 1.2:
class myClass {
static func myMethod1() {
}
class func myMethod2() {
}
static var myVar1 = ""
}
func doSomething() {
myClass.myMethod1()
myClass.myMethod2()
myClass.myVar1 = "abc"
}
What is the difference between a static function and a class function? Which one should I use, and when?
If I try to define another variable class var myVar2 = ""
, it says:
Class stored properties not yet supported in classes; did you mean 'static'?
When this feature is supported, what will the difference be between a static variable and a class variable (i.e. when both are defined in a class)? Which one should I use, and when?
(Xcode 6.3)
Why are static variables considered evil?I am a Java programmer who is new to the corporate world. Recently I've developed an application using Groovy and Java. All through the code I wrote used quite a good number of statics. I was asked by the senior technical lot to cut down on the number of statics used. I've googled about the same, and I find that many programmers are fairly against using static variables.
I find static variables more convenient to use. And I presume that they are efficient too (please correct me if I am wrong), because if I had to make 10,000 calls to a function within a class, I would be glad to make the method static and use a straightforward Class.methodCall()
on it instead of cluttering the memory with 10,000 instances of the class, right?
Moreover statics reduce the inter-dependencies on the other parts of the code. They can act as perfect state holders. Adding to this I find that statics are widely implemented in some languages like Smalltalk and Scala. So why is this opposition to statics prevalent among programmers (especially in the world of Java)?
PS: please do correct me if my assumptions about statics are wrong.
What is the Python equivalent of static variables inside a function?What is the idiomatic Python equivalent of this C/C++ code?
void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
Adding a favicon to a static HTML pageI have a few static pages that are just pure HTML, that we display when the server goes down. How can I put a favicon that I made (it's 16x16px and it's sitting in the same directory as the HTML file; it's called favicon.ico) as the "tab" icon as it were? I have read up on Wikipedia and looked at a few tutorials and have implemented the following:
<link rel="icon" href="favicon.ico" type="image/x-icon"/>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
But it still doesn't want to work. I am using Chrome to test the sites. According to Wikipedia .ico is the best picture format that runs on all browser types.
I could not get this to work locally although the code checks out it will only really work properly once the server started serving the site. Just try pushing it up to the server and refresh your cache and it should work fine.
What is the difference between static func and class func in Swift?I can see these definitions in the Swift library:
extension Bool : BooleanLiteralConvertible {
static func convertFromBooleanLiteral(value: Bool) -> Bool
}
protocol BooleanLiteralConvertible {
typealias BooleanLiteralType
class func convertFromBooleanLiteral(value: BooleanLiteralType) -> Self
}
What's the difference between a member function defined as static func
and another one defined as class func
? Is it simply that static
is for static functions of structs and enums, and class
for classes and protocols? Are there any other differences that one should know about? What is the rationale for having this distinction in the syntax itself?
How do I create class (i.e. static) variables or methods in Python?
Static Initialization BlocksAs far as I understood the "static initialization block" is used to set values of static field if it cannot be done in one line.
But I do not understand why we need a special block for that. For example we declare a field as static (without a value assignment). And then write several lines of the code which generate and assign a value to the above declared static field.
Why do we need this lines in a special block like: static {...}
?
There is no static
keyword in Kotlin.
What is the best way to represent a static
Java method in Kotlin?
I read a few threads here about static methods, and I think I understand the problems misuse/excessive use of static methods can cause. But I didn't really get to the bottom of why it is hard to mock static methods.
I know other mocking frameworks, like PowerMock, can do that but why can't Mockito?
I read this article, but the author seems to be religiously against the word static
, maybe it's my poor understanding.
An easy explanation/link would be great.
static