Gr. X File 9. Encapsulation-1
Gr. X File 9. Encapsulation-1
static keyword
static keyword will make the member belong to the class and not an instance.
Only 1 copy exist for the entire class when members are declared as ‘static’.
Thus, data members or member functions not created for the instance but
created for the class are declared with the keyword static. Only 1 sharable copy
exist for the entire class for these types of members.
E.g.
class abc
{
int a,b; //instance members – so multiple copies can exist(depending on
number of instances/objects)
static int c; //class member – so single copy exists for the entire class
void function1()
{ ……….
……….
}
static void function2()
{ ……….
……….
}
} // class ends
Question : Differentiate between instance methods and class methods.
Ans.
instance methods class methods
1. Declared without any special 1. Declared with the keyword ‘static’.
keyword
2. method can be called by 2. method can be called by the class name.
object/instance
3. E.g. n = sc.nextInt(); 3. E.g. d = Math.sqrt(100);
Scope of variables (is always the set of braces for which they are declared)
Types of variables :
There are mainly two types of variables :
1. Global Variables 2. Local variables
(declared at a class level) (declared at a function level)
Example :
class abc
{
int a, b; //instance variables
static int c; //class variable
void fn1(int x, int y)//x,y – parameter/argument variables
{
int z; //local variable
z=x + y;
System.out.println(z);
}
……………
}//class ends
Package:
Package is a collection of related or similar classes. To use the readymade
package in our class, keyword ‘import’ is used.
Examples of java API packages: lang, util, io etc.
Library Classes:
Classes present in Java Library inside a package are called Library classes.
Examples of Library classes: Math, String, Scanner etc.