Showing posts with label static variables. Show all posts
Showing posts with label static variables. Show all posts

Thursday, 20 February 2014

Hiding Fields

Within a class, a field that has the same name as a field in the super class hides the super class's field, even if their types are different.

Hiding Static fields
Example
class SuperClass{
 static String data = "I am a string variable";
}

class SubClass extends SuperClass{
 static int data = 10; 
 
 public static void main(String args[]){
  System.out.println(data);
  System.out.println(SuperClass.data);
 }
} 
 
Output
10
I am a string variable

Observe the above program, the variable data is of type String in the super class and type int in the sub class. Even though the types are different, the variable in the sub class hides the variable in the super class.

Hiding instance fields
class SuperClass{
 String data = "I am a string variable";
}
    
class SubClass extends SuperClass{
 int data = 10; 

 void printData(){
  System.out.println(data);
  System.out.println(super.data);
 }

 public static void main(String args[]){
  SubClass obj1 = new SubClass();
  obj1.printData();
 }
} 
   
Output
10
I am a string variable


Usage Of Polymorphism                                                 Super keyword                                                 Home

Sunday, 9 February 2014

class variables

As we know, instance variables are associated with object, where as class variables associated with class, i.e, available for all objects.
    Syntax
         static dataType variableName;

    Example
        static int count;

static variables are accessed by using class name.

    Syntax to access static variable
        ClassName.variablename

Example : program to count number of objects created for a class 
class Person{
 static int count =0;
 
 Person(){
  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.count);
 }
}


Output
Number Of persons created are 2


Constructors                                                 Static Metods                                                 Home