super Usage:
1) super.<variable_name> refers to the variable of variable of parent class.
2) super() invokes the constructor of immediate parent class.
3) super.<method_name> refers to the method of parent class.
2) super() invokes the constructor of immediate parent class.
3) super.<method_name> refers to the method of parent class.
//Parent class or Superclass class Parentclass { int num=100; } //Child class or subclass class Subclass extends Parentclass { /* I am declaring the same variable * num in child class too. */ int num=110; void printNumber(){ System.out.println(num); } public static void main(String args[]){ Subclass obj= new Subclass(); obj.printNumber(); } }
Output:
110
110
Static keyword in java
The static keyword is used in java mainly for memory management. Static keyword are used with variables, methods, blocks and nested class. Static is a keyword that are used for share the same variable or method of a given class. This is used for a constant variable or a method that is the same for every instance of a class. The main method of a class is generally labeled static.
No object needs to be created to use static variable or call static methods, just put the class name before the static variable or method to use them. Static method can not call non-static method.
In java language static keyword can be used for following
- variable (also known as class variable)
- method (also known as class method)
- block
- nested class
Static variable
If any variable we declared as static is known as static variable.
- Static variable is used for fulfill the common requirement. For Example company name of employees,college name of students etc. Name of the college is common for all students.
- The static variable allocate memory only once in class area at the time of class loading.
Advantage of static variable
Using static variable we make our program memory efficient (i.e it saves memory).
When and why we use static variable
Suppose we want to store record of all employee of any company, in this case employee id is unique for every employee but company name is common for all. When we create a static variable as a company name then only once memory is allocated otherwise it allocate a memory space each time for every employee.
Syntax for declare static variable:
public static variableName;
No comments:
Post a Comment