قراءة
عرض

Static Variables (Class Variables)

A static variable belongs to a class and is not part of the state of individual instance objects. Only one copy of each static variable exists. It is often called class variables and it is frequently useful to have a variable that is shared by all instance objects of a class or, if public, can be used by any client of a class.
Static variables exist at class scope and support such behavior.

A class variable is declared using static keyword and may be explicitly initialized.
Class variables have several distinct uses:
As variable shared by all instances of the class. As such they can be described as 'global' to the class scope and are typically declared as private.
As variable accessible to any client (مستفيد) of the class. As such they are effectively global to an entire program and would need to be declared as public. Such variables, being updatable from any piece of code, are seriously dangerous and hence extremely rare.
As constants declared as final (that will be explained next lectures). Typically such constants are made public to be used anywhere within a program. Many java library classes make use of such public static final variables. By convention their names are split using uppercase letter.
The variable initialization rules state that static variables must be initialized either explicitly (بشكل واضح) or by taking the default value of the variable type (القيمة التي تفرضها قواعد اللغة). In addition, a static variable initialization can't refer to any static variables declared after its own declaration. Hence, the following code is not allowed:

Example 1

Class Example{
………….
Error
Static int a=b*10;
Static int b=3;
………….. }


Class Example{
Correct
………….
Static int b=3;
Static int a=b*10;
…………..
}

Error

public class A {
public int b=3;
public static int a=3*b; }

Correct

public class A {
public static int b=3;
public int a=3*b; }

When a variable is defined at the class level, it is accessible from every member method of the class. However you must remember that static members of a class are different from those that are not. Since non-static members belong to objects (class instances) and not to the class itself, you cannot, for example, use non-static variables or methods from within static methods.
For example parts of the following code will cause an error non static variable accessed by static method


Example 2

public class C {

int n=0;
static int s=0;
int getn() {
return n; //OK }
int gets() {
return s; //OK }
static int get2n() {
return n; //ERROR!! } }

Example 3

Lec 17

Example 4

public class StaticVariable{public static int noOfInstances;public StaticVariable(){noOfInstances++;}}


Public class Main(){public static void main(String[] args){StaticVariable sv1 = new StaticVariable();System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);StaticVariable sv2 = new StaticVariable();System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);System.out.println("No. of instances for st2 : " + sv2.noOfInstances);StaticVariable sv3 = new StaticVariable();System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);System.out.println("No. of instances for sv2 : " + sv2.noOfInstances);System.out.println("No. of instances for sv3 : " + sv3.noOfInstances);}}

The output will be:

Lec 17



General in Java programming, it is a common practice to place static members before non-static members, and constructor methods before any other method. Therefore on top of variables preceding (يسبق) methods, static variables must precede (يسبق) non-static ones, and static methods precede non-static ones but come after constructors. For example:

Example 5 (للاطلاع فقط)

class Circle {

static double PI = 3.14;
double radius;
Circle (double radius) {
this.radius = radius; }
static double area (Circle c) {
return PI * c.radius * c.radius;}
double area () {
return area(this);}


Static/Class Methods
A class method, also known as a static method is called by prefixing it with a class name, eg, Math.max(i,j);. Curiously (من الغريب), it can also be qualified with an object, which will be ignored, but the class of the object will be used.
To differentiate an instance method from a class method, one of the modifiers used in the signature of the class method is declared as static. The static modifier is reserved for methods that normally be invoked by an object; these are known as class methods. The static modifier may also be used with variables that do not belong to a single object. There are two types of methods:
● Instance methods and ● Static methods
From outside the defining class, an instance method is called by prefixing it with an object, which is then passed as an implicit parameter to the instance method, eg, inputTF.setText("");
A static method is called by prefixing it with a class name, eg, Math.max(i,j);. Curiously, it can also be qualified with an object, which will be ignored, but the class of the object will be used.

Example 6

public class A {
public static int b=3;
public static int a=3*b;
public static void set1(){
a=100; }
public void set2(){
a=200;}

public void set3(){

a=300;}
public static void set4(){
a=400; } }


public class Main {
public static void main(String[] args) {
A aa=new A();
aa.set1(); System.out.println(aa.a+" "+aa.b); System.out.println(A.a+" "+A.b);
aa.set3(); System.out.println(aa.a+" "+aa.b); System.out.println(A.a+" "+A.b);
aa.set4(); System.out.println(aa.a+" "+aa.b); System.out.println(A.a+" "+A.b);
aa.set2(); System.out.println(aa.a+" "+aa.b); System.out.println(A.a+" "+A.b);

A.set1(); System.out.println(aa.a+" "+aa.b); System.out.println(A.a+" "+A.b);
// A.set2(); Error
// A.set3(); Error
A.set4(); System.out.println(aa.a+" "+aa.b); System.out.println(A.a+" "+A.b);
} }

The output is:

100 3
100 3

300 3

300 3


400 3
400 3

200 3

200 3

100 3

100 3

400 3

400 3
Example 7
Here is a typical static method.
class MyUtils {
. . .
public static double mean(int[] p) {
int sum = 0; // sum of all the elements
for (int i=0; i<p.length; i++) { sum += p[i]; }
return ((double)sum) / p.length;
}//endmethod mean
. . . }


How can we call (invoked) this method?
Why declare a method static
The above mean() method would work just as well if it wasn't declared static, as long as it was called from within the same class. If called from outside the class and it wasn't declared static, it would have to be qualified (uselessly) with an object. Even when used within the class, there are good reasons to define a method as static when it could be.
Documentation. Anyone seeing that a method is static will know how to call it. Similarly, any programmer looking at the code will know that a static method can't interact with instance variables, which makes reading and debugging easier.
Efficiency. A compiler will usually produce slightly more efficient code because no implicit (ضمني) object parameter has to be passed to the method.

Calling static methods

There are two cases:
Called from the same class
Just write the static method name. Eg,
// Called from inside the MyUtils class
double avgAtt = mean(attendance);
Called from outside the class
If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined. For instance methods, this is the object that the method will access. For static methods, the class name should be specified. Eg,
// Called from outside the MyUtils class.
double avgAtt = MyUtils.mean(attendance);
If an object is specified before it, the object value will be ignored and the class of the object will be used.
Alternate call
What's a little peculiar, and not recommended, is that an object of a class may be used instead of the class name to access static methods. This is bad because it creates the impression that some instance variables in the object are used, but this isn't the case.

Example 8 (important case)

public class Animal {public static void hide() {System.out.println(“The hide method in Animal.”);}public void override() {System.out.println(“The override method in Animal.”);} }
The second class, a subclass of Animal, is called Cat:
public class Cat extends Animal {
public static void hide(){ System.out.println(“The hide method in Cat.”); }
public void override() {System.out.println(“The override method in Cat.”);}}
public class Main{
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = (Animal)myCat;
myAnimal.hide(); myAnimal.override();}}


The Cat class overrides the instance method in Animal called override and hides (هنا ليست override( the class method in Animal called hide. The main method in this class creates an instance of Cat, casts it to an Animal reference, and then calls both the hide and the override methods on the instance. The output from this program is as follows:

The hide method in Animal.

The override method in Cat.
The version of the hidden method that gets invoked is the one in the superclass, and the version of the overridden method that gets invoked is the one in the subclass. For class methods, the runtime system invokes the method defined in the compile-time type of the reference on which the method is called. In the example, the compile-time type of myAnimal is Animal. Thus, the runtime system invokes the hide method defined in Animal. For instance methods, the runtime system invokes the method defined in the runtime type of the reference on which the method is called. In the example, the runtime type of myAnimal is Cat. Thus, the runtime system invokes the override method defined in Cat.
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = new Cat();
myAnimal.hide();
myAnimal.override();
myCat.hide();
myCat.override();

run:

The hide method in Animal.
The override method in Cat.
The hide method in Cat.
The override method in Cat.

public static void main(String[] args) {

Cat myCat = new Cat();
Animal myAnimal = (Animal)myCat;
myAnimal.hide();
myAnimal.override();
myCat.hide();
myCat.override();
} }
run:
The hide method in Animal.
The override method in Cat.
The hide method in Cat.
The override method in Cat.
An instance method cannot override a static method, and a static method cannot hide an instance method.


The static method can be inherited.
Example 9
class Scott {
public static void abc() {
System.out.println("aaa");
}

}
public class Group extends Scott {
…………}
public class Main{
public static void main(String[] args){
Group.abc();
}

}

The static method can be redefining and the static method cannot be overriding

Example 10


class Scott {
public static void abc() {
System.out.println("aaa");
}
}
public class Group extends Scott {
public static void abc() { System.out.println("zzz");}}
Public class Main{
public static void main(String[] args){
Group.abc();
}

}

the output is :zzz

What is the difference between method overriding and redefining in java?
Overriding is closely connected to polymorphism. Redefining method is similar to Overriding but you cannot expect those redefined methods to deliver polymorphism. The concept of redefining is used when it involves static methods.

An abstract class may have static fields and static methods. You can use these static members with a class reference—for example,
AbstractClass.staticMethod()—as you would with any other class.


Abstract class cannot be instantiated. If I don't declare the methods in Abstract class static, how can I call them?
Answer : you need to extend the class

Explain the following and support your answer by programming example?

Static method cannot be overridden. Instance methods cannot be overridden by static method. (H.W.).

Example 11

Consider the following example:
public abstract class One {
protected int x,y;
public static void f1(){
System.out.println("static f1 from class One");}
abstract public void f2();
public void f3(){
System.out.println("f3 from One class");
} }

public class Two extends One {
private int a;
public static void f1(){
// super.f1(); error so it is redefining not overriding
System.out.println("redefining method f1 from class Two"); }
public void f2(){
// super.f2(); Error
System.out.println(" defining abstract method f2 from class Two");}
public void f3(){
System.out.println("method overriding from class Two"); } }


public class Main {
public static void main(String[] args) {
Two t=new Two();

t.f1(); t.f2(); t.f3()

One.f1(); Two.f1(); } }

The output is:

redefining method f1 from class Two
defining abstract method f2 from class Two
method overriding from class Two
static f1 from class One
redefining method f1 from class Two

if we modify class Two as below:

public class Two extends One {
private int a;
public static void f1(){
// super.f1(); error so it is redefining not overriding
System.out.println("redefining method f1 from class Two");
}
public void f2(){
// super.f2(); Error
System.out.println(" defining abstract method f2 from class Two");}
public void f3(){
System.out.println("method overriding from class Two");
super.f3();
} }


The output is:
redefining method f1 from class Two
defining abstract method f2 from class Two
method overriding from class Two
f3 from One class
static f1 from class One
redefining method f1 from class Two

if we modify class Two as below:

public class Two extends One {
private int a;
public static void f1(){
// super.f1(); error so it is redefining not overriding
System.out.println("redefining method f1 from class Two"); }
public void f2(){
// super.f2(); Error
System.out.println(" defining abstract method f2 from class Two");}
public void f3(){
System.out.println("method overriding from class Two");
super.f3(); this.f1(); this.f2(); } }


The output is:

redefining method f1 from class Two

defining abstract method f2 from class Two
method overriding from class Two
f3 from One class
redefining method f1 from class Two
defining abstract method f2 from class Two
static f1 from class One
redefining method f1 from class Two

public class A {

public static int x;
public A(){
x=x+1;}
public void print (){
System.out.println("x="+x);}
}

public class Main {


public static void main(String[] args) {
//A.x=1;
A a1=new A();
a1.print();
A a2=new A();
a2.print();
System.out.println(A.x);
A a_array[]=new A[5];
for(int i=0;i<5;i++){
a_array[i]=new A();
}
System.out.println(A.x);
a_array[0].print();
}
}




رفعت المحاضرة من قبل: HS Alqaicy
المشاهدات: لقد قام عضوان و 90 زائراً بقراءة هذه المحاضرة








تسجيل دخول

أو
عبر الحساب الاعتيادي
الرجاء كتابة البريد الالكتروني بشكل صحيح
الرجاء كتابة كلمة المرور
لست عضواً في موقع محاضراتي؟
اضغط هنا للتسجيل