Professional Documents
Culture Documents
Session 11
Session 11
Variable arguments
• Variable number of arguments in a function/method
• This feature is called varargs and it is short-form for variable-length
arguments
• A variable-length argument is specified by three periods(…)
• While defining method signature, always keep varargs at last
• A method can have only one varargs parameter
class Test2
{
// Takes string as a argument followed by varargs
static void fun2(String str, int ...a)
{
System.out.println("String: " + str);
System.out.println("Number of arguments is: "+ a.length);
}
class TestBank{
public static void main(String args[]){
SBI b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
PNB c=new PNB();
System.out.println("Rate of Interest is: "+c.getRateOfInterest()+" %");
}}
‘final’ keyword
• Final is a keyword in Java that is used to restrict the user and can be
used in many respects. Final can be used with:
• Class
• Methods
• Variables
• When a class is declared as final, it cannot be extended further
• A method declared as final cannot be overridden
• Once a variable is assigned with the keyword final, it always contains
the same exact value
‘final’ keyword
• final prevents overriding
• final prevents inheritance
Output?
class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}
}
Output
class Bike{
final void run(){System.out.println("running");}
}
//What is in interface Z?
Default methods in Interface
• Default methods allows the interfaces to have methods with
implementation without affecting the classes that implement the
interface
• Preceded with the keyword ‘default’ before the method name
• Default method comes with Java 8 (also static method in interface
comes with Java 8 only)
interface TestInterface
{
public void square(int a);
default void show()
{
System.out.println("Default Method Executed");
}
}
class TestClass implements TestInterface
{
public void square(int a)
{
System.out.println(a*a);
}
public static void main(String args[])
{
TestClass d = new TestClass();
d.square(4);
d.show();
}}
interface TestInterface
{
public void square (int a);
static void show()
{
System.out.println("Static Method Executed");
}
}
class TestClass implements TestInterface
{
public void square (int a)
{
System.out.println(a*a);
}
public static void main(String args[])
{
TestClass d = new TestClass();
d.square(4);
TestInterface.show();
}