Total Pageviews

Tuesday, 28 June 2011

Access Modifier and VARARGS.

ACCESS MODIFIER
Access modifier,
helps us to know the visibility of the variables and the member class, defined in a class .Here visibility means that whether we can accessed by other sub-classes and classes from different packages or not.There are four types of access modifier in java : public, protected ,private and default


Public: Any variable or methods declared as public can be accessed by any other code, within or outside the package in which it is defined.

Protected : The variable or method declare as protected , can be accessed by any class and sub classes in the same package but also to the subclasses in other package.

Private :  If we declare as private ,then they are accessible only with their own class. They cannot be inherited bu subclasses and therefore not accessible in subclasses . It behaves like a method declared as final. It prevents the method from being subclassed.

Default : In java , if we don't mention any access modifier then by default , it is marked as "default" access modifier .They can be accessed only and within the same package .

VARARGS:
variable represent variable length arguments in methods, which is one of the features introduced by J2SE 5.0 .
syntax :
 <access specifier> <static> void method-name(object...arguments)

In the above syntax, the method contains argument called varargs in which object is the type of a aregument, ellipsis(...) is the key to varargs and arguments is the name of the variable.
Varargs help us to build a method, in which we can pass arguments at the run time for an unspecified number of parameters.The arguments passed in varargs are of string type. This string type can be parsed into other types as per our requirement.

example :
//normal method declaration
public static void sample(String name , String location , String mailid){
//body of the method;
}
//using varargs
public static void sample( String...var_name);
//body of the method;
}
In the first case we have declared three parameters for our method but in the second case , we have declared only one parameter but it works similar to the first type, i.e we can pass all the three arguments as we did in the first type.

No comments:

Post a Comment