Difference Between Static and Final

Difference between Static and final?

The static keyword can be used in 4 scenarios

  • static variables
  • static methods
  • static blocks of code
  • static nested class

Let's look at static variables and static methods first.

Static variable

  • It is a variable which belongs to the class and not to object (instance).
  • Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
  • A single copy to be shared by all instances of the class.
  • A static variable can be accessed directly by the class name and doesn’t need any object.
  • Syntax: Class.variable

Static method

  • It is a method which belongs to the class and not to the object (instance).
  • A static method can access only static data. It can not access non-static data (instance variables) unless it has/creates an instance of the class.
  • A static method can call only other static methods and can not call a non-static method from it unless it has/creates an instance of the class.
  • A static method can be accessed directly by the class name and doesn’t need any object.
  • Syntax: Class.methodName()
  • A static method cannot refer to this or super keywords in anyway.

Static class

Java also has "static nested classes". A static nested class is just one which doesn't implicitly have a reference to an instance of the outer class.

Static nested classes can have instance methods and static methods.

There's no such thing as a top-level static class in Java.

Side note:

main method is static since it must be be accessible for an application to run before any instantiation takes place.

final keyword is used in several different contexts to define an entity which cannot later be changed.

  • A final class cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes are final, for example java.lang.System and java.lang.String. All methods in a final class are implicitly final.

  • A final method can't be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.

  • A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a blank final variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases.

Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.

When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. Once it has been assigned, the value of the final variable cannot change.

Difference between a static and a final static variable in Java

You are making a huge mix of many different concepts. Even the question in the title does not correspond to the question in the body.

Anyways, these are the concepts you are mixing up:

  • variables
  • final variables
  • fields
  • final fields
  • static fields
  • final static fields

The keyword static makes sense only for fields, but in the code you show you are trying to use it inside a function, where you cannot declare fields (fields are members of classes; variables are declared in methods).

Let's try to rapidly describe them.

  1. variables are declared in methods, and used as some kind of mutable local storage (int x; x = 5; x++)

  2. final variables are also declared in methods, and are used as an immutable local storage (final int y; y = 0; y++; // won't compile). They are useful to catch bugs where someone would try to modify something that should not be modified. I personally make most of my local variables and methods parameters final. Also, they are necessary when you reference them from inner, anonymous classes. In some programming languages, the only kind of variable is an immutable variable (in other languages, the "default" kind of variable is the immutable variable) -- as an exercise, try to figure out how to write a loop that would run an specified number of times when you are not allowed to change anything after initialization! (try, for example, to solve fizzbuzz with only final variables!).

  3. fields define the mutable state of objects, and are declared in classes (class x { int myField; }).

  4. final fields define the immutable state of objects, are declared in classes and must be initialized before the constructor finishes (class x { final int myField = 5; }). They cannot be modified. They are very useful when doing multithreading, since they have special properties related to sharing objects among threads (you are guaranteed that every thread will see the correctly initialized value of an object's final fields, if the object is shared after the constructor has finished, and even if it is shared with data races). If you want another exercise, try to solve fizzbuzz again using only final fields, and no other fields, not any variables nor method parameters (obviously, you are allowed to declare parameters in constructors, but thats all!).

  5. static fields are shared among all instances of any class. You can think of them as some kind of global mutable storage (class x { static int globalField = 5; }). The most trivial (and usually useless) example would be to count instances of an object (ie, class x { static int count = 0; x() { count++; } }, here the constructor increments the count each time it is called, ie, each time you create an instance of x with new x()). Beware that, unlike final fields, they are not inherently thread-safe; in other words, you will most certainly get a wrong count of instances of x with the code above if you are instantiating from different threads; to make it correct, you'd have to add some synchronization mechanism or use some specialized class for this purpose, but that is another question (actually, it might be the subject of a whole book).

  6. final static fields are global constants (class MyConstants { public static final double PI = 3.1415926535897932384626433; }).

There are many other subtle characteristics (like: compilers are free to replace references to a final static field to their values directly, which makes reflection useless on such fields; final fields might actually be modified with reflection, but this is very error prone; and so on), but I'd say you have a long way to go before digging in further.

Finally, there are also other keywords that might be used with fields, like transient, volatile and the access levels (public, protected, private). But that is another question (actually, in case you want to ask about them, many other questions, I'd say).

what's the difference between static, final and const members at compile time in Dart?

static is to declar class level members (methods, fields, getters/setters).
They are in the class' namespace. They can only be accessed from within the class (not subclasses) or with the class name as prefix.

class Foo {
static bar() => print('bar');

void baz() => bar(); // ok
}

class Qux extens Foo {
void quux() => bar(); // error. There is no `bar()` on the `Qux` instance
}

main() {
var foo = Foo();
foo.bar(); // error. There is no `bar` on the `Foo` instance.
Foo.bar(); // ok
}

const is for compile time constants. Dart allows a limited set of expressions to calculate compile time constants.
const instances are canonicalized. This means multiple const Text('foo') (with the same 'foo' parameter value) are canonicalized and only one single instance will be created no matter where and how often this code occurs in your app.

class Foo {
const Foo(this.value);

// if there is a const constructor then all fields need to be `final`
final String value;
}
void main() {
const bar1 = Foo('bar');
const bar2 = Foo('bar');
identical(bar1, bar2); // true
}

final just means it can only be assigned to at declaration time.

For instance fields this means in in field initializers, by constructor parameters that assign with this.foo, or in the constructor initializer list, but not anymore when the constructor body is executed.

void main() {
final foo = Foo('foo');
foo = Foo('bar'); // error: Final variables can only be initialized when they are introduced
}

class Foo {
final String bar = 'bar';
final String baz;
final String qux;

Foo(this.baz);
Foo.other(this.baz) : qux = 'qux' * 3;
Foo.invalid(String baz) {
// error: Final `baz` and `qux` are not initialized
this.baz = baz;
this.qux = 'qux' * 3;
}
}

In PHP, what is the difference between final static and const?

final

The methods or classes can not be modified by a child class. This prevents class inheritance, method-overriding and/or redefinition of methods.

Only class definitions and/or methods inside a class can be defined as
final.

static

Declares class methods or properties as a static value so that you have access to them without instantiating an object. These are shared between parent and child-classes.

A class definition can not be static unlike final.

const

These create a constant value for a class. The constant values will get changed and can NOT be changed by a method in either parent or child-class.

Class constants are allocated per instance of the class.


const is a type specifier in itself. It can not be put along with public/private/static etc. final, as mentioned before can be used along with any method or class definitions and hence; applicable with all of them. static can not be applied to class definitions but can be used for class properties.

UPDATE

modifiers are allowed for class constants since PHP 7.1.0.

class Foo {
public const bar = 5;
private const baz = 6;
}

To summarise, final static can not be used to define something like:

class X {
final static x = 5;
}

which is why you have a const.

Difference between final variables vs static final variables

But even if i declare a variable only final, then it remains the same
for all the objects as i need to initialize them in the program itself
and not at the run time.

No, non-static final members can be initialized in the constructor. They cannot be re-assigned after that.

static vs final swift

So, after a while research I would say that static is used for a property that can be accessed without created a class instance and final is a modifier for a class that from this class nobody can be inherent.

What is the difference between static func and final class func in swift

Just because a final class function can't be overridden doesn't mean it's statically dispatched. A final class function be override a superclass non-final class function. Such a method call must be dynamically dispatched.

static is merely an alias for final class. They behave the same:

class C1 { class func foo() {} }
class C2: C1 { override final class func foo() {} }
class C3: C1 { override static func foo() {} }

Difference between static and const variable in Dart

The declaration for cons must be using const. You have to declare it as static const rather than just const.

static, final, and const mean entirely distinct things in Dart:

static means a member is available on the class itself instead of on instances of the class. That's all it means, and it isn't used for anything else. static modifies members.

final means single-assignment: a final variable or field must have an initializer. Once assigned a value, a final variable's value cannot be changed. final modifies variables.

const has a meaning that's a bit more complex and subtle in Dart. const modifies values. You can use it when creating collections, like const [1, 2, 3], and when constructing objects (instead of new) like const Point(2, 3). Here, const means that the object's entire deep state can be determined entirely at compile time and that the object will be frozen and completely immutable.

Const objects have a couple of interesting properties and restrictions:
They must be created from data that can be calculated at compile time. A const object does not have access to anything you would need to calculate at runtime. 1 + 2 is a valid const expression, but new DateTime.now() is not.
They are deeply, transitively immutable. If you have a final field containing a collection, that collection can still be mutable. If you have a const collection, everything in it must also be const, recursively.
They are canonicalized. This is sort of like string interning: for any given const value, a single const object will be created and re-used no matter how many times the const expression(s) are evaluated. In other words:

getConst() => const [1, 2]; 

main() {
var a = getConst();
var b = getConst();
print(a === b); // true
}

I think Dart does a pretty good job of keeping the semantics and the keywords nicely clear and distinct. (There was a time where const was used both for const and final. It was confusing.) The only downside is that when you want to indicate a member that is single-assignment and on the class itself, you have to use both keywords: static final.

Also:

I suggest you to have a look at this question

What is the difference between the "const" and "final" keywords in Dart?

Does it make sense to define a static final variable in Java?

It makes sense, yes. This is how constants are defined in Java.

  • final means that the variable cannot be reassigned - i.e. this is the only value it can have
  • static means that the same value is accessible from each instance of the class (it also means it can be accessed even without an instance of the class where it is declared)

(private here means this constant is accessible only to the current class (all of its instances and its static methods))



Related Topics



Leave a reply



Submit