Lecture 3A
 Value vs Reference
 Overloading
 Inheritance
 Overriding
 OverrideVsOverload
 InheritanceExample
 This's & Super's
 AnotherExample
 
Abstraction
 Static Meth & Var.
Lectures

1A: Introduction
1B: Java Intro
2A: BuildingBlocks
2B: Objects
3A: More Objects
3B: Exceptions
       & Threads
4A: Waves
4B: Nuclear &
       Particle
5A: AWT
5B: More AWT
      & Graphics
6A:Detectors &
      Simulation
6B: LHC/Atlas &
     RandomSims    
7A: Swing
7B: Java2D
8A: Java Apps
8B: Dialogs &
    MoreClasses
9A: Java I/O
9B: Utilities,
        Unicode
10A: More
    Threading
10B: File
    Handling
11A: Array,Print,
    Images
11B: SimplePhysics
    Simulation
12A: Tips &
    Techniques
12B: More Tips &
    Techniques
13A: Satellite
    
Simulations
13B: Intro to Java
    Networking
14A: Java Servers
14B: HTTP Server
15A: ServerClient
15B: ServerClient
   Expt.Simulation
16A: Course
          Review
16B: ExerciseTest
        Discussion

    Contacts
    Description
    Exercises
    Index
    Outline
    Q&A
    Resources
    StudentInfoForm
    Student Pages
    What's New

 

Home : Lectures : Lecture3A : Static Methods & Variables
Static Variables & Methods

In place of global variables as in C/C++, Java allows variables in a class to be declared static:

   public class A {
    static int k_var;
    ....
   }

A single memory location is assigned to this variable and it exists and is accessible even when no instances of class_A are created.

These static variable is also called class variables, since they belong to the class as a whole.

If a class property is also declared final, then it becomes a global constant (i.e. can't be altered):

   public class A {
    final static int k_var;
    ....
   }

This is how the pi value Math.PI is created in the Math class.

Similarly, methods can also be declared static, and are called class methods

   public class A {
    static void A_method(float x){...}
    ....
   }   

These class methods also can be called even when no instance of the class exists. The code in a class method can only refer to static variables and the argument variables.

The Math class that we have used, for example, contains static methods to carry out various mathematical functions without having to create a Math object.

public class mathExample {
  static double pi=3.14;
  double b=3;
  double func(double x){
     return ( 4.0*Math.sin(x)**2);   
  }
  static double sfunc(double x){
     return (3.0*x);
   }
   static double tfunc(double x){
     return (3.0*x*pi);
   }
   static double wfunc(double x){
     return (3.0*x*b);=> Error!
                     Cannot use nonstatic
                     variable in a class
                     method.
   }
}

 

Home Lectures Resources Index Contacts Students


Physics Simulations with JavaTM
KTH, Kurskod: 5A1418
Curator: Clark S. Lindsey