Sunday, 9 February 2014

class methods

As we know instance methods are associated with an object, where as class methods are associated with class.

Syntax
    static dataType methodName(parameters){
    }

Example
    static int getNoOfEmployees(){
    }

Class methods also called as static methods. Static methods called with class name.

Syntax to call class Methods
ClassName.methodName();

Example
class Person{
 static private int count =0;
 
 Person(){
  count++;
 }

 static int getNoOfPersons(){
  return count;
 }
}


class PersonTest{
 public static void main(String args[]){
  Person personA = new Person();
  Person personB = new Person();
  System.out.println("Number Of persons created are " + Person.getNoOfPersons());
 }
}

Output  
Number Of persons created are 2

Some Points To Remember
1. You can't call instance method from static method.

     Example
class Person{
 static int getNoOfPersons(){ 
  setName("HI");
  return 1;
 }
 
 void setName(String s){
 
 }
}


When you try to compile the above program, compiler throws below error
Person.java:4: error: non-static method setName(String) cannot be referenced from a static context
setName("HI");
^
1 error

2. Static methods can't access instance variables
    Example
class Person{
 String name;
 
 static int getNoOfPersons(){
  name="Hi";
  return 1;
 }
}

When you try to compile the above program, compiler throws below error

Person.java:5: error: non-static variable name cannot be referenced from a static context
name="Hi";
^
1 error

3. Applying static for top level class is wrong in java
    Example
static class Person{
 
}

When you try to compile, compiler throws the below error
Person.java:1: error: modifier static not allowed here
static class Person{
^
1 error

4. Static fields are initialized at the time of class loading, where as instance variables are initialized at the time of object creation

5. Just like instance methods, we can overload static methods also

Static Variables                                                 Initializer Blocks                                                 Home

No comments:

Post a Comment