why we should use static keyword in dart in place of abstract? - flutter

I m preparing a class in my flutterfire project and their I want to use some method Which can't change further so that I want to know consept of static keyword 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.
Static methods
Static methods (class methods) don’t operate on an instance, and thus don’t have access to this. They do, however, have access to static variables.
void main() {
print(Car.numberOfWheels); //here we use a static variable.
// print(Car.name); // this gives an error we can not access this property without creating an instance of Car class.
print(Car.startCar());//here we use a static method.
Car car = Car();
car.name = 'Honda';
print(car.name);
}
class Car{
static const numberOfWheels =4;
Car({this.name});
String name;
// Static method
static startCar(){
return 'Car is starting';
}
}

static keyword in dart used to declare a variable or method that belongs to just the class not the instants which means the class has only one copy of that variable or method and those static variables(class variables) or static methods(class methods) can not be used by the instances created by the class.
for example if we declare a class as
class Foo {
static String staticVariable = "Class variable";
final String instanceVariable = "Instance variable";
static void staticMethod(){
print('This is static method');
}
void instanceMethod(){
print('instance method');
}
}`
the thing here to remember is static variables are created only once and every instance crated by the class has different instance variables. therefore you can not call static variables form the class instances.
following codes are valid,
Foo.staticVariable;
Foo().instanceVariable;
Foo.staticMethod();
Foo().instanceMethod();
there for following codes will give errors
Foo().staticVariable;
Foo.instanceVariable;
Foo().staticMethod;
Foo.instanceMethod
Use of static variables and methods
you can use static variables when you have constant values or common values that are relevant for the class.
you can read more here - https://dart.dev/guides/language/language-tour#class-variables-and-methods

Related

do instances point to their own classes (to access methods)?

How can the compiler know what method is an object calling?
lets say for example:
class Person
{
string name;
int age;
void walk()
{
// do something with name and age
}
}
so I already know that it actually translate to a method which takes the instance itself as the first parameter, but how can the object itself access it?
do all objects of class person point somewhere where all the class methods are, and maybe even static variables (and methods)?

class access control: What if there is readonly access controller?

While I was using class, I found that some attributes, especially the ones which are boolean, are often read by other instances. For example,
class Node{
private:
int item;
bool visited;
public:
bool isVisited(){return visited;}
void bar(){
...
visited=true;
...
}
};
class Graph{
private:
vector<Node> nodes;
public:
void bar(int idx){
if(nodes[idx].isVidited()){
...
nodes[idx].foo();
...
}
}
}
In that case if visited is only changed by the methods of the class Node, then the access controller of the attribute visited shouldn't always be private in perspective of reading. What if there is an access controller 'readonly' that is opened to reading, closed to writing? I think that is useful when defining state attributes. Will there be any side effects?
Have you tried marking the Graph class as friend inside the Node class?
This facilitates accessing the private members of the Node class by the Graph class.
In some languages, there is getter/setter which works as an api of a private value.
It seems like a public value, but internally the methods control the private member variable, not the code with '=' operator itself.
//TYPESCRIPT
class Foo{
private _name:string
constructor(n:string){this._name=n}
get name(){return this._name}
//set name(n:string){this._name=n}
}
const foo=new Foo('Jack jack')
console.log(foo.name) //[LOG]: "Jack jack"
foo.name='hudson' //[ERR]: Cannot set property name of #<Foo> which has only a getter
The code above shows how a readonly property is set. There is only a getter which delivers exactly the same value of the private member variable '_name', but since setter is not defined, only the class itself can change the value and is not able to edit from outside of the class.

Why i need to declare a variable that have the same name of class and script?

public class CanvasManager : MonoBehaviour
{
public static CanvasManager Instance; // = lobby
[SerializeField]
private LobbyFunction _lobbyFunction;
public LobbyFunction LobbyFunction
{
get { return _lobbyFunction; }
}
...
below is one of the reference
private void Start()
{
GameObject lobbyCanvasGO = CanvasManager.Instance.LobbyFunction.gameObject;
...
I am confused that is it necessary to have the same name of canvasmanager that it is declared , and why there is no error when I sayCanvasManager.Instance.LobbyFunction ,it made me confused since LobbyFunction is belonged to CanvasManager, not Instance.
Finally , sometimes ,
private LobbyFunction _lobbyFunction;
private LobbyFunction LobbyFunction
{
get { return _lobbyFunction; }
}
Sometimes,
private LobbyFunction _lobbyFunction;
public LobbyFunction LobbyFunction
{
get { return _lobbyFunction; }
}
Thanks for your patience reading this, and your help would be greatly appreciated, thanks!
Your class is named CanvasManager, but you cannot statically access it right away.
You created a static member variable in CanvasManager, which holds a reference to a CanvasManager. This is called the singleton pattern.
You can only access static members without a class instance. But in the case of singletons, you create a single instance of the class (usually assigned in Start() or in getInstance() (lazy) after checking if it exists) which you can then access statically through "Instance".
Now, Instance is a static variable holding a reference to a single instance of CanvasManager. So, you can then access non-static members and functions of CanvasManager, if you access "Instance".
Think about it like this:
CanvasManager local_instance = new CanvasManager();
local_instance.non_static_member = value; // this works
CanvasManager.static_member = value; // this works
CanvasManager.non_static_member = value; // won't work.
And now one step further, you access the instance via CanvasManager.Instance.*
CanvasManager.Instance.non_static_member = value; // works!
Explanation of static vs non-static:
normal variables:
Variables needs memory. So usually you create 5 instances of CanvasManager and each instance can have different values. Because each instance reserves memory for each Variable. But if you want to change one, you need to explicitly talk to that instance. You could manage them in a List or by having multiple variables in Code like manager1, manager2...
Think of it as books, where each copy can be modified (write notes into it)
static variables
If you create a static variable, the memory is reserved once for the Class. You can then directly get/set this static variable from anywhere in Code without the need of a Reference to an instance.
Think of it as an online blog, where changes are applied for everyone, being accessible from everywhere. The text exists once in the blog database.
Singletons:
If you only want a single CanvasManager and not 5, you could attach it to any GameObject and access it. But every other script needs a reference, like public CanvasManager my_manager which you need to assign in inspector. As an alterantive, you could use
GameObject.Find("CanvasManagerObject").getComponent<CanvasManager>()
in each script... If only there was a better way to access this CanvasManager from everywhere...
The singleton pattern allows you to get a reference to a single, nonstatic instance of the CanvasManager, while it doesn't even need a GameObject it can attach to.
Naming
You are talking about "it has to have the same name" - this is not true. You can name the instance whatever you like. CanvasManager.MyCustomlyNamedInstance would work too. But the MyCustomlyNamedInstance must be a static variable in the CanvasManager class, or any other class. You could have a GameManager that manages your instances, so GameManager.MyCanvasManagerInstance would work too.

Java and main()

I'm messing around with Eclipse(and java in general) for the first time in about a year. among the things I have forgotten is the following:
I have a function (void callvote() that I am hoping will be activated by my main function (that is, automatically, relatively early in the program). I currently have it within the same class (body) as the main function itself.
I try to call it withcallvote(); and get an error, "- Cannot make a static reference to the non-static method callvote() from the type body"
my function callvote is, at the moment, in the space below main and simply says
public void callvote()
{
}
am i committing a horrible sin by putting more functions in the same class as main?
is this a relatively easy fix that I missed somehow?
What does this error mean?
Have I woken Azatoth with this code?
Thanks in advance,
Tormos
Without the static modifier callvote is implicitly an instance method - you need an instance of a class to call it.
You could mark it as static also:
public static void callvote() ...
Or create an instance of the declaring class:
MyClass instance = new MyClass();
instance.callvote();
main() is a static method, meaning you can call it directly from a class whereas non-static members can only be called from an object. In order for you to call the callvote() method you need to first instantiate an object of your class:
public static void main(String [ ] args) {
MyClass myObject = new MyClass();
myObject.callvote();
}
Another way to avoid the error is to make you callvote() method static as well, but it's usually not what you want to do (but it depends on the nature of your class and method).
This post describes some of the dangers with the overuse of static methods: Class with single method -- best approach?
Try this:
public class Main {
public static void main(String[] args) {
new Main().callvote()
}
}
the main() entry point of your java program is static. You cannot call a non static method from a static one.
So you have to instanciate your Class first and call the method after.

How non-static is accessible in static context in this program?

I am having confusion with the following code:
class A
{
int x;
static void F(B b) {
b.x = 1; /* Ok,
I want to know how is this ok, in a static block how a non static
instance variables are called because as I know that static block
gets memory at compile time before execution of a single command
while non static at run time and static method accessing a non static
variable which is not created yet please elaborate me on this
*/
}
}
class B: A
{
static void F(B b) {
b.x = 1; // Error, x not accessible
}
}
Nothing gets memory at compile time. Static fields are indeed placed in the static block of memory when the type gets initialized. Call stacks for static methods are allocated at run time exactly like in case of instance methods.
Now, why static methods don't have access to the instance fields. Consider this:
class A {
public int Value;
static int GetValue() {
return Value;
}
}
There you have a class with an instance field and a static method. Now, somewhere else you try this:
var a1 = new A();
a1.Value = 5;
var a2 = new A();
a2.Value = 10;
int result = A.GetValue();
Now, if compiler allowed this, what value would the result get? 5 or 10 or something else? This just doesn't make sense, because static methods are declared for class as a whole and aren't aware of instances of this class. So in the code of static method you don't know how many (if any) instances of this class exist and can't access their instance fields.
Hope this makes a little sense.
Either you changed the code in question a bit or I didn't read very carefully. Seems like it's completely different problem right now. The variable x is indeed not accessible for the class B because of its level of protection (default in C# is private). Class A can modify X because it's declared in class A and visible to its method. Class B can't do it (you must make x protected or public for that).